【发布时间】:2017-04-25 14:11:35
【问题描述】:
我在 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(); ?>
【问题讨论】:
-
显示您的表单代码
-
将表单的代码添加到问题中。
-
变量
$model的类是什么? -
$model被初始化为$model = new ChooseAgeCategoriesForm();,因此ChooseAgeCategoriesForm派生自yii\base\Model。