首页 > 解决方案 > Yii2:为什么 kartik\select2 小部件没有填充然后我尝试更新模型?

问题描述

我有 ActiveRecord 模型和该模型的更新形式的视图。我也在模型类中有getter和setter,看起来像这样

public function setTopvisorGoogleRegion($value)
{
    $this->myvalue = $value;
    return(true);
}

public function getTopvisorGoogleRegion()
{
    return([1 => '123']); //I return this array for show you essence of the problem
}

此代码中的以下逻辑 $model->topvisorgoogleregion 必须返回 [1 => '123']

鉴于我有下一个代码

<?php echo($form->field($model, topvisorgoogleregion)->textInput());?>
<?php echo $form->field($model, 'topvisorgoogleregion')->widget(Select2::classname(), [
    'data' =>  [1 => '123', 2 => '456'],
    'options' => [
        'id'=>'projectCtrl',
        'placeholder' => 'Select option',
        'multiple' => true
    ],
    'pluginOptions' => [
        'allowClear' => true,
        'tags' => true, 
    ],

]);
?>

当我打开表单时,我想查看 Select2 中已选择的选项 1 => '123'。这在逻辑上是因为当已经存在的记录正在更新时,ActiveRecord 获取已经存储在模型中的数据(在这种情况下使用 getter)并用这些数据填充视图中的字段(在使用 textInput 的第一个字段中,我看到文本“数组”,因为模型中的 getter返回数组)。但是当我打开更新页面时 Select2 是空的。怎么了?

如果我删除第一个字段(textInput)没有任何变化

标签: phpactiverecordyii2widget

解决方案


我找到了解决方案 - 在 getter 中我需要提供 ActiveQuery 对象,而不是数组。我不知道它为什么以及如何工作,但它确实有效


推荐阅读