Zend_Form - How to addValidator after the form has been submitted
I have 2 te开发者_运维技巧xt fields in my form.
- TextFieldA - not required
- TextFieldB - not required
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 apreValidate()
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'sisValid($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.
精彩评论