Yii2:为什么未填充kartik \ select2小部件,然后尝试更新模型?

时间:2019-03-17 11:33:44

标签: php activerecord yii2 widget

我有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的第一个字段中,我会看到文本“ Array”,因为模型中有getter返回数组)。但是当我打开更新页面时Select2为空。怎么了?

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

1 个答案:

答案 0 :(得分:0)

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