I am using the following (simple) code for a model to be used with a form in yii2:
class ChooseAgeCategoriesForm extends Model
{
public $ageCategories;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
['ageCategories', 'safe'],
[['ageCategories'], 'each', 'rule' => ['integer']],
];
}
}
However, then trying to load the model like this:
$model = new ChooseAgeCategoriesForm();
if ($model->load(Yii::$app->request->post())) {
$acIDs = $model->ageCategories;
}
The code is never executed. In fact, $model->load returns Bool(false) but $model->errors is empty. Dumping the content of post yields this result:
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" } }
So yes, the field is actually sent and filled with an array of numbers. What don't I see here, what is the problem? Thanks in advance. I also tried to add ['ageCategories', 'exist', 'allowArray' => true], as another rule, but this does not work either. Any ideas?
Form code
As requested, the code of the form itself:
<?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's class?$modelis initialized as$model = new ChooseAgeCategoriesForm();, henceChooseAgeCategoriesFormwhich is derived fromyii\base\Model.