I have 2 text fields in my form.
After user submitted the form, How to add validator / setRequired(true) to TextFieldB if the value of TextFielA is not empty?
I see two approaches in addition to @Marcin's idea.
Conditionally call setRequired() on the relevant elements by creating a preValidate() method on the form and calling it in your controller. [Really the same idea as @Marcin, but pushed down into the form itself, keeping the controller a bit leaner.]
Create a custom validator called something like ConditionallyRequired that accepts as an option the fieldname of the "other field". Then attach this validator to each element, configuring it with the name of the "other" element. Then in the validator's isValid($value, $context) method, conditionally test $value if $context['otherfield'] is non-empty.
You could do as follows:
if ($this->getRequest()->isPost()) {
$textFieldA = $yourForm->getElement('TextFieldA');
$textFieldB = $yourForm->getElement('TextFieldB');
if (!empty($_POST['TextFieldA'])) {
$textFieldB->setRequired(true);
}
if (!empty($_POST['TextFieldB'])) {
$textFieldA->setRequired(true);
}
if ($mainForm->isValid($_POST)) {
// process the form
}
}
Basically, you add the validators after the post, but before the form is validated. Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With