Kartik Select2 Not Select Corretly

Hello.

I’m using Select2 in a form, work well but not select corretly.




echo $form->field($model,'Estado_idEstado')->widget(Select2::classname(),[

            'model'=>$model,

            'attribute'=>'Estado_idEstado',

            'data'=>array_merge([""=>""],ArrayHelper::map(Estado::find()->all(),'idEstado','estado')),

            //'options' => ['placeholder' => 'Seleccione Técnico']

        ]);

var_dump($model->Estado_idEstado);

var_dump(ArrayHelper::map(Estado::find()->all(),'idEstado','estado'));



I don’t know why the default option is not ‘Terminado’.

Thanks.

I was not able to translate what the default value above is, because I do not see in your code. Can you please explain, where you have set this value (is it in your controller or model)?

Edit: I see this in your attached thumbnail. Refer the solution below.

One way to set a default value of ‘Terminado’ can be the following:




if ($model->isNewRecord && !isset($model->Estado_idEstado)) {

    $model->Estado_idEstado = 1; // the id for 'Terminado'; 

}

echo $form->field($model, 'Estado_idEstado')->widget(Select2::classname(), [

    'data' => ArrayHelper::map(Estado::find()->all(),'idEstado','estado')),

    'options' => ['placeholder' => 'Seleccione Técnico']

]);



Here are some other suggestions:

[list=1]

[*]Do not use array_merge for generating data (as it reindexes). Instead use array union.

[*]The widget will do the above for you automatically if you set the placeholder property. So you do not need to do that.

[*]You can simplify the ActiveField widget method as well (no need to repeat the model & attribute being passed).

[/list]

Your code can be simplified to the following below:




echo $form->field($model, 'Estado_idEstado')->widget(Select2::classname(), [

    'data' => ArrayHelper::map(Estado::find()->all(),'idEstado','estado')),

    'options' => ['placeholder' => 'Seleccione Técnico']

]);



Thanks Kartik, array_merge was the problem.

Now it’s ok.

Thank you very much. :D