0

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");
    }
}
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
dr Anton
  • 125
  • 1
  • 7

1 Answers1

1

Yes you can, but you have a wrong assignment of variable i.e $params in the last condition elseif (count($params)<2) you are counting $params instead of the $this->ingredients array. And you do not need to have the first check, adding the attribute to the required rule is enough to check if it is empty when submitted.

change the validation function to

public function checkIsArray( $attribute , $params ) {

    if ( count ( $this->ingredients ) > 5 ) {
        $this->addError ( $attribute , "Choose No more than 5" );
    } elseif ( count ( $this->ingredients ) < 2 ) {
        $this->addError ( $attribute , "Choose No less than 2" );
    }
}

I just tested it before posting with the kartik\Select2 multiselect and it works just fine, but if it still reacts the same you need to add the controller/action code hope it helps you out.

Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68