3
votes

I have 2 text fields in my form.

  1. TextFieldA - not required
  2. TextFieldB - not required

After user submitted the form, How to add validator / setRequired(true) to TextFieldB if the value of TextFielA is not empty?

2

2 Answers

2
votes

I see two approaches in addition to @Marcin's idea.

  1. 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.]

  2. 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.

1
votes

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.