Yii2:模型没有加载数组

时间:2017-04-25 14:11:35

标签: php yii2

我使用以下(简单)代码将模型与yii2中的表单一起使用:

class ChooseAgeCategoriesForm extends Model
{

    public $ageCategories;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            ['ageCategories', 'safe'],
            [['ageCategories'], 'each', 'rule' => ['integer']],
        ];
    }
}

但是,然后尝试加载这样的模型:

$model = new ChooseAgeCategoriesForm();

if ($model->load(Yii::$app->request->post())) {
        $acIDs = $model->ageCategories;
}

代码永远不会执行。实际上,$model->load会返回Bool(false),但$model->errors为空。转储post的内容会产生以下结果:

array(2) { ["_csrf"]=> string(56) "SzhjdWIuc0oIQSA0BEs4BDp8KzYEXwM5CG80RhNBRDkPUzIXO1gBew==" ["ageCategories"]=> array(9) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> string(1) "4" [4]=> string(1) "5" [5]=> string(1) "6" [6]=> string(1) "7" [7]=> string(1) "9" [8]=> string(2) "10" } }

所以是的,该字段实际上是发送并填充了一组数字。我在这里看不到什么,问题是什么?提前致谢。我还尝试将['ageCategories', 'exist', 'allowArray' => true],添加为另一个规则,但这也不起作用。有什么想法吗?

表单代码

根据要求,表单代码本身:

<?php $form = ActiveForm::begin([
    'action' => Url::to(['/result/team-result']),
    'method' => 'post',
    'options' => ['id' => 'chooseAgeCategory', 'style' => "margin-bottom: 15px;"]
]); ?>

<?= Select2::widget([
    'name' => 'ageCategories',
    'id' => 'ac-id',
    'value' => $acIDs,
    'data' => ArrayHelper::map(AgeCategory::find()->all(), 'id', 'name'),
    'options' => ['multiple' => true, 'placeholder' => Yii::t('view', 'Select Age Category')],
    'pluginEvents' => [
        "change" => "function() { this.form.submit(); }",
    ]
]) ?>

<?php $form->end(); ?>

2 个答案:

答案 0 :(得分:1)

我建议您使用Select2属性model,以便自动链接到缓和加载过程的字段,并使用模型的验证功能:

<?= Select2::widget([
    'name' => 'ageCategories',
    'id' => 'ac-id',
    'value' => $acIDs,
    'data' => ArrayHelper::map(AgeCategory::find()->all(), 'id', 'name'),
    'options' => ['multiple' => true, 'placeholder' => Yii::t('view', 'Select Age Category')],
    'pluginEvents' => [
        "change" => "function() { this.form.submit(); }",
    ]
]) ?>

答案 1 :(得分:1)

请更改您的select2小部件代码,如下所示。 Yii2包装模型名称,字段名称为

  

ChooseAgeCategoriesForm [ageCategories]

如果您检查表格,您就会知道。所以你必须在select2小部件中给出模型值。

<?= Select2::widget([
    'model' => $model,
    'attribute' => 'ageCategories',
    'id' => 'ac-id',
    'value' => $acIDs,
    'data' => ArrayHelper::map(AgeCategory::find()->all(), 'id', 'name'),
    'options' => ['multiple' => true, 'placeholder' => Yii::t('view', 'Select Age Category')],
    'pluginEvents' => [
        "change" => "function() { this.form.submit(); }",
    ]
]) ?>

参考:http://demos.krajee.com/widget-details/select2