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

问题描述 投票:0回答:1

我正在与此创建表单:

<?= $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个或更多值?

php drop-down-menu yii2 maxlength
1个回答
0
投票

您可以这样做。在模型中声明一个验证器函数。

public function limitSelection($attribute,$params)
{
if(count($this->$attribute)>3)
    {
        $this->addError($attribute,"You are only allowed to select 3 or less items for ".$attribute);      
     }
 }

然后以下列方式声明规则。

public function rules()

{       

    return [    

..................other rules...................... 

       ['job_category', 'required','message'=>"Select at least one item for {attribute}"],           

       ['job_category', 'limitSelection']
        ];
}
© www.soinside.com 2019 - 2024. All rights reserved.