Question

I have a form with several subforms on it. I have an isValid method for the form where I check if only one particular subform is valid. For example, I must check if subform2 validates properly. If subform validates, the whole form should be validated successfully, even if other subforms have wrong values. They just should not be validated. I tried something like this:

if($subform->isValidPartial($_POST))
    return true;
}else{
    return false;
}

But with no succes. This code always returns true. When the whole form is validated normally without the isValid overriden, subforms are validated properly, but thye are all validated.

Était-ce utile?

La solution

isSubFormValid will return true if at least one subform is valid. You can specify subform name or pass null.

class My_Form extends Zend_Form
{
    public function isSubFormValid($name = null, array $data = null)
    {
        if (is_null($name)) {
            $subForms = $this->getSubForms();
        } else {
            $subForms = array($this->getSubForm($name));
        }

        foreach ($subForms as $subForm) {
            if ($subForm->isValid($data)) {
                return true;
            }
        }    

        return false;
    }    
}

Usage example:

class Example extends My_Form
{
    public function init()
    {
        $subForm1 = new Zend_Form_SubForm();
        $subForm1->addElement($this
            ->createElement('text', 'name')
            ->setRequired(true));

        $subForm2 = new Zend_Form_SubForm();
        $subForm2->addElement($this
            ->createElement('text', 'name')
            ->setRequired(true));

        $this->addSubForm($subForm1, 'form1');
        $this->addSubForm($subForm2, 'form2');

        $this->addElement($this->createElement('submit', 'send'));
    }    
}

/* ... */
public function indexAction()
{
     $form = new Example();

     if ($this->_request->isPost()) {
         if ($form->isSubFormValid(null, $this->_request->getPost())) {
             die('is valid');
         }
     }

     $this->view->form = $form;
}

/* ... */
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top