How to add id preix for field in activeForm? - yii2

i have two forms holds the same model attributes, since Yii2 generate the field id to be ModelName-fieldName so the field generated will be as follow:
<select name="Channel[channel]" class="form-control" id="channel-description">
i have tried to use fieldConfig in Activeform but it doesn't add the id to the field itself.

You should simply use the third parameter of ActiveForm::field() :
$options : The additional configurations for the field object.
e.g. :
$form->field($model, 'channel', ['inputOptions' => ['id' => 'channel-description']])
Read more about ActiveForm::field().
But if you really want to add a prefix to all your fields ids, you should override ActiveForm.

If you want save input id structure "{model}-{attribute}".
Use yii\helpers\Html::getInputId() for generate "{model}-{attribute}" input id and complete it with your custom prefix.
$form->field($model, 'name')->textInput(['id' => 'custom-' . Html::getInputId($model, 'name')])

If you set a custom id for the input element, you may need to adjust the [[$selectors]] accordingly.
<?= $form->field($searchModel, 'regId',[
'selectors' => ['input' => '#company-vacancy-regId'],
'inputOptions' => ['id' => 'company-vacancy-regId'],
])->widget()?>

Related

yii2 autocompelete not work for me

i have table that have developer_id, name, family .etc columns
i want to show suggest name in input in view i did something like this but this give me a input whitout any suggestion and autocompelte
why?
$data = Developers::find()
->select(['name as value', 'name as label','developer_id as id'])
->asArray()
->all();
echo AutoComplete::widget([
'name' => 'dname',
'id' => 'ddd',
'clientOptions' => [
'source' => $data,
'autoFill'=>true,
'minLength'=>'1',
'select' => new JsExpression("function( event, ui ) {
$('#aa').val(ui.item.id);
}")],
]);
?>
<input id="aa" value="" type="hidden">
I copied and pasted your code in one of my views. I just changed your model so I am using one of my models (tables). Your code works perfectly in my view. So I think you should check if the problem is one of these:
You are not correctly importing one of these:
use backend\models\Developers;
use yii\jui\AutoComplete;
use yii\web\JsExpression;
Your table Developers is empty
In the part of your code that says:
->select(['name as value', 'name as label','developer_id as id'])
Are you sure your table developer has the columns name and developer_id?

Yii2: Kartik Select2: Initial Value from Model Attribute

I have a Model who has a column (attribute) that stored a comma separated value of IDs.
For Example,
Movie has a column "Genre" that includes more than one genre, e.g.: 40,20,1,3
How can I use Select2 widget to show these values separated when 'multiple' => true
And how can I save them back into comma-separated value as a string. I want a solution that will allow for quick flexibility. I know you can implode and explode the string but seems too much.
Any help appreciated
If I remember correctly pass the default option as part of the $options configuration for the widget:
echo $form->field($model, 'model_attribute_name')->widget(Select2::className(), [
'data' => $data
'options' => [
'class' => 'form-control',
'placeholder' => 'Choose Option...',
'selected' => 40
],
'pluginOptions' => [
'allowClear' => true,
],
])->label('Select2 Form Field');
This is from memory for grain fo salt here. The documentation at http://demos.krajee.com/widget-details/select2 is not very specific about how to do this.
I don't believe you can do that. Select2 sends the data in post as an array, so you would still need to use implode before saving. What i would do instead is in your model class:
class MyModel extends \yii\db\ActiveRecord {
$public myArrayAttribute;
...
public function beforeSave($insert) {
if (parent::beforeSave($insert)) {
$this->myAttribute = implode(',', $this->myArrayAttribute);
return true;
}
return false;
}
public function afterFind() {
parent::afterFind();
$this->myArrayAttribute = explode(',', $this->myAttribute);
}
}
This way myArrayAttribute will hold the values from the comma separated field as an array. Of course you will need to add validation rules for it and use it instead of your other attribute in create and update forms.
if you're displaying a form with already populated fields, maybe you want to update an already existing object, and you want to display the already saved value for the Select2 field, use 'data' => [ 1 => 'Some value' ], where 1 is the value, associated to the value displayed in the form. You can retrieve stuff to put in data from DB beforehand.
Source: https://github.com/kartik-v/yii2-widget-select2/issues/37

How to change field's name attribute in Symfony Entity type Field

I am new to symfony and have researched a lot but couldn't find a way out
Here is my field add property
$builder->add('busownlvlone','entity',array('required'=>false,'class' => 'MyBundle:BusOwnLvlOne','property' => 'business_name','empty_value' => 'Choose an option', 'label' => 'Select Business', 'attr' => array('style' => 'width:230px')
))
Here is what I get in View
<select style="width:230px" name="mybundle_maptype[busownlvlone]" id="mybundle_maptype_busownlvlone"><option value="">Choose an option</option></select>
I want to customize Name property of this field basically I want to turn it into an array sth like
name="mybundle_maptype[busownlvlone][]"
If I add multiple then the select box changes to multi select so this cannot be an option.Is there any other way out like adding a custom name etc?
Made a Custom Element Type which extended Entity Type to resolve this

yii2 hidden input value

In Yii2 I'm trying to construct hidden input
echo $form->field($model, 'hidden1')->hiddenInput()->label(false);
But I also need it to have some value option, how can I do that ?
Use the following:
echo $form->field($model, 'hidden1')->hiddenInput(['value'=> $value])->label(false);
Changing the value here doesn't make sense, because it's active field. It means value will be synchronized with the model value.
Just change the value of $model->hidden1 to change it. Or it will be changed after receiving data from user after submitting form.
With using non-active hidden input it will be like that:
use yii\helpers\Html;
...
echo Html::hiddenInput('name', $value);
But the latter is more suitable for using outside of model.
simple you can write:
<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'abc value'])->label(false); ?>
You can do it with the options
echo $form->field($model, 'hidden1',
['options' => ['value'=> 'your value'] ])->hiddenInput()->label(false);
you can also do this
$model->hidden1 = 'your value';// better put it on controller
$form->field($model, 'hidden1')->hiddenInput()->label(false);
this is a better option if you set value on controller
$model = new SomeModelName();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->group_id]);
} else {
$model->hidden1 = 'your value';
return $this->render('create', [
'model' => $model,
]);
}
Like This:
<?= $form->field($model, 'hidden')->hiddenInput(['class' => 'form-control', 'maxlength' => true,])->label(false) ?>
You can use this code line in view(form)
<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'your_value'])->label(false) ?>
Please refere this as example
If your need to pass currant date and time as hidden input :
Model attribute is 'created_on' and its value is retrieve from date('Y-m-d H:i:s') ,
just like:"2020-03-10 09:00:00"
<?= $form->field($model, 'created_on')->hiddenInput(['value'=>date('Y-m-d H:i:s')])->label(false) ?>
<?= $form->field($model, 'hidden_Input')->hiddenInput(['id'=>'hidden_Input','class'=>'form-control','value'=>$token_name])->label(false)?>
or
<input type="hidden" name="test" value="1" />
Use This.
You see, the main question while using hidden input is what kind of data you want to pass?
I will assume that you are trying to pass the user ID.
Which is not a really good idea to pass it here because field() method will generate input
and the value will be shown to user as we can't hide html from the users browser. This if you really care about security of your website.
please check this link, and you will see that it's impossible to hide value attribute from users to see.
so what to do then?
See, this is the core of OOP in PHP.
and I quote from Matt Zandstr in his great book PHP Objects, Patterns, and Practice fifth edition
I am still stuck with a great deal of unwanted flexibility, though. I rely on the client coder to change a ShopProduct object’s properties from their default values. This is problematic in two ways. First, it takes five lines to properly initialize a ShopProduct object, and no coder will thank you for that. Second, I have no way of ensuring that any of the properties are set when a ShopProduct object is initialized. What I need is a method that is called automatically when an object is instantiated from a class.
Please check this example of using __construct() method which is mentioned in his book too.
class ShopProduct {
public $title;
public $producerMainName;
public $producerFirstName;
public $price = 0;
public function __construct($title,$firstName,$mainName,$price) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
}
And you can simply do this magic.
$product1 = new ShopProduct("My Antonia","Willa","Cather",5.99 );
print "author: {$product1->getProducer()}\n";
This produces the following:
author: Willa Cather
In your case it will be something semilar to this, every time you create an object just pass the user ID to the user_id property, and save yourself a lot of coding.
Class Car {
private $user_id;
//.. your properties
public function __construct($title,$firstName,$mainName,$price){
$this->user_id = \Yii::$app->user->id;
//..Your magic
}
}
I know it is old post but sometimes HTML is ok :
<input id="model-field" name="Model[field]" type="hidden" value="<?= $model->field ?>">
Please take care
id : lower caps with a - and not a _
name : 1st letter in caps

Getting value from url for filter field in GridView

In my grid view I have added my own filter. But as you can see I had to use "value" to get the value for that input field from url. Other filter fields doesn't require anything, they pick up value automatically, but custom filter field doesn't. I type something in, it accepts and search and after that, field is empty.
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'tableOptions'=>['class'=>'table table-striped table-hover table-bordered responsive',],
'columns' => [
[
'attribute'=>'date_created',
'filter'=>Html::activeTextInput($BreederResultsSearch, 'date_created', ['class'=>'js-datepicker', 'value'=>isset($_GET["BreederResultsSearch"])?$_GET["BreederResultsSearch"]["date_created"]:NULL]),
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
In your filter you can add:
$this->date_created=Yii::$app->getRequest()->getQueryParam('date_created',NULL);
Your problem could be, that you don't have a public attribute in your SearchModel that gets properly validated by rules. If the attribute is not in the rules (for your given scenario) it doesn't take the value but sets the field/attribute to be null.
This part of the docu explains how filtering with SearchModels and attributes works. http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#filtering-data
Edit: Also to mention is maybe, that the filters don't get their values from the url, but from the according attributes of the model that is transfered to the view (filterModel of your gridview)
Edit:
Is the searchModel the same model you use for the activeInputField in the filter? It should! or did you just rename it here?