Yii2,为 select2 小部件设置默认值

Yii2, set default value for select2 widget

 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 小部件设置默认值?

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

$myModel = new \app\models\myModel;
$myModel->attributes = \Yii::$app->request->post('myModel');