Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set selected or default value in select2 yii2?

How to set selected or default value in select2 yii2? i've tried using 'value' => $myvalue and 'initValue' => $myValue

Is there any solution? Thank You.

I've just found solution. here if you want to set default value or selected value for select :

<?php $model->group = yourdefaultValue ?>
<?=$form->field($model, 'group')->label('Group Name')->widget(Select2::classname(),
[
     'data' => ArrayHelper::map(Group::find()->all(),'id','name', 'kategori'),
     'options' => ['placeholder' => 'Select Phone Number'],
     'pluginOptions' => [
           'allowClear' => true,
           'minimumInputLength' => 2,
     ],
]);
?>
like image 355
adn Avatar asked Jan 03 '23 21:01

adn


2 Answers

I had same situation. But adding 'value' key solved my problem.

Select2::widget([
   'name' => ['1'=> 'A', '2' => 'B', '3' => 'C'],
   'value' => [1,3], // value to initialize
   'data' => $data
]);

Above example will automatically select A & C.

Perhaps if you could add your sample data structure here then it will be helpful for us to help you.

Please see the link for more details: https://github.com/kartik-v/yii2-widgets/issues/87#issuecomment-46200711

like image 112
atiq1589 Avatar answered Jan 17 '23 10:01

atiq1589


<?php $form = ActiveForm::begin() ?>
<?=$form->field($model, 'group')->label('Group Name')->widget(Select2::classname(),
    [
        'data' => ArrayHelper::map(Group::find()->all(),'id','name', 'kategori'),
        'options' => ['placeholder' => 'Select Phone Number', 'value' => 1],
        'pluginOptions' => [
            'allowClear' => true,
            'minimumInputLength' => 2,
        ],
    ]);
?>
<?php $form::end()?>

You just need set default value in selection.

'options' => ['placeholder' => 'Select Phone Number', 

'value' => $model->id

]
like image 34
noxom Avatar answered Jan 17 '23 11:01

noxom