1
 use kartik\widgets\Select2;

 echo Select2::widget([
    'model' => $myModel,
    'name' => 'company[]',
    'options' => [
        'placeholder' => 'Select a company ...',
        'multiple' => true,
    ],
    'value' => 6, //doesn't work
    'initValueText' => '6', //doesn't work
    'pluginOptions' => [
        'allowClear' => true,
        'ajax' => [
            'url' => Url::to(['/company/default/get-company-list']),
            'dataType' => 'json',
            'data' => new JsExpression('function(term,page) {
                return {term : term.term};
            }'),
            'results' => new JsExpression('function(data,page) {return {results:data.results}; }'),
        ],
        'initSelection' => new JsExpression('function(element, callback) {
            $(element).val(6); //doen't work
            callback({"text" : "Vendor B", "id" : 6}); // it does only set text, not id
        }'),
    ],
]);
... many many select2 form below too, that named 'company[]'

After form submit, if user come back to this page, I want to set what user selected as default.

How can I set default value for Select2 widget?

Nerd
  • 121
  • 1
  • 10

1 Answers1

1

When you update the model, it will automatically have the last selected value.

$myModel = new \app\models\myModel;
$myModel->attributes = \Yii::$app->request->post('myModel');
n099y
  • 414
  • 2
  • 16
  • Thank you for your answer, Is it able to have array-attribute in a model? for now I'm just using a dummy model for Select2, actually it doesn't do anything., I think I need to create a view-model for storing them , am I right? please advise, – Nerd Jul 07 '15 at 08:40
  • Yes that is right, you won't get full functionality until you create a model and relationships and whatever else is needed. Arrays are catered for like in checkbox groups and the like. – n099y Jul 07 '15 at 09:52