I have a model, for example SomeForm. There is a field. This field contains an array of selected options. Is it possible to write a rule for this field to check how many items were selected? I need to write a condition, that user has to check minimum 2 options and maximum 5.
I tried something like this, but it doesn't work (the form can be submitted if at least one option is selected)
public function rules()
{
return [
[['ingredients'], 'required'],
['ingredients', 'checkIsArray']
];
}
public function checkIsArray($attribute, $params)
{
if (empty($this->ingredients)) {
$this->addError($attribute, "config cannot be empty");
}
elseif (count($this->ingredients)>5) {
$this->addError($attribute, "Choose more");
}
elseif (count($params)<2) {
$this->addError($attribute, "Choose less");
}
}