In my Form I have a Fieldset, that contains two elements foo and bar. The business rule for them is, that one has to be set. So, the fieldset is valid, when foo OR bar is set, and invalid, when no-one is set.
I solved this as follows:
public function getInputFilterSpecification()
{
return [
'foo' => [
'required' => empty($this->get('bar')->getValue())
],
'bar' => [
'required' => empty($this->get('foo')->getValue())
],
];
}
Working. But there is still an issue with the error messages: If bot fields are empty, the user gets for every field the message "Value is required and can't be empty". The user thinks then, he has to fill in both fields.
How to customize the error message for a required field, in order to show correct messages like "Value for foo is required and can't be empty, if bar is not set." and "Value for bar is required and can't be empty, if foo is not set."?
You could wirte a custom ValidatorChain by extending the default Chain
You could then override this method:
By default this method will only return true if ALL validators return true, but it also has access to the context - this means you can get all other field values too.
It's simple to amend the logic to then check if either of the validators are true return true.
You then simply attach all the fields you want to be "one of these required"