开发者

Zend_Form - How to addValidator after the form has been submitted

I have 2 te开发者_运维技巧xt 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜