Reputation: 53
I would like to set a rule to limit the number of option visitors can select in a field multiple select.
I tried this, but it doesn't work
$validator
->add('colors._ids', [
'multiple'=>[
'rule'=>['multiple', ['max'=>3]],
'message'=>'Please select only one color'
]
])
->requirePresence('colors._ids', 'create');
// ->allowEmpty('colors._ids');
return $validator;
In the view the field is displayed like that:
echo $this->Form->input('colors._ids', ['options' => $colors, 'multiple' => true]);
Using debugtoolkit I can read:
Thank you very much for your help
Upvotes: 1
Views: 972
Reputation: 268
I had a similar problem to you and to solve it I ended up using a custom validation rule.
So for example:
->add('tablename', 'custom', [
'rule' => function($value) {
return (bool)(is_array($value['_ids']) && count($value['_ids']) === 3);
},
'message' => 'Please select 3.'
]);
This rule will make sure the user selects 3 items from the select. No more no less, I'm sure you could adapt this for your problem.
Upvotes: 2