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[]'

表单提交后,如果用户返回此页面,我想将用户选择的内容设置为默认值。

如何设置 Select2 小部件的默认值?

4

1 回答 1

1

当您更新模型时,它将自动具有最后选择的值。

$myModel = new \app\models\myModel;
$myModel->attributes = \Yii::$app->request->post('myModel');
于 2015-07-07T07:33:20.080 回答