猿问

如何为 Yii2 ActiveForm dropDownList 设置最大选择?

我正在用这个创建一个表单:

<?= $form->field($model, 'job_category')
     ->dropDownList($jobCategoryDropDown, ['options' => $jobCategoryOptionArray, 'multiple' => 'multiple'])
     ->label('Ngành nghề - chuyên môn (Bắt buộc) <span class="help-required"> * </span>') ?>

如何限制用户最多选择 3 个或更多值?


白猪掌柜的
浏览 93回答 1
1回答

RISEBY

你可以这样做。在模型中声明一个验证器函数。public function limitSelection($attribute,$params){if(count($this->$attribute)>3)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->addError($attribute,"You are only allowed to select 3 or less items for ".$attribute);&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp;}&nbsp;}然后通过以下方式声明规则。public function rules(){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; return [&nbsp; &nbsp;&nbsp;..................other rules......................&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;['job_category', 'required','message'=>"Select at least one item for {attribute}"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;['job_category', 'limitSelection']&nbsp; &nbsp; &nbsp; &nbsp; ];}
随时随地看视频慕课网APP
我要回答