Validate form but not subform

357 Views Asked by At

I have a Zend_Form whose sub-form is only required in certain circumstances. The parent form and the sub-form both have required fields. The sub-form will not always be filled but when any of its elements are filled, they should all be filled.

<?php
class Cred extends Zend_Form
{

  public function init()
  {
    $title = new Zend_Form_Element_Text('Title');
    $title->setLabel('Title')
        ->setRequired(TRUE);
    $this->addElement($title);

    $award = new Zend_Form_Element_Text('Awarded');
    $award->setLabel('Awarded On')
        ->setRequired(TRUE)
        ->addValidator('date');
    $this->addElement($award);

    $subform = new Zend_Form_SubForm();

    $proof = new Zend_Form_Element_File('Documentation');
    $proof->setLabel('Documentation')
        ->setRequired(TRUE)
        ->addValidator('Size', false, 409600) // limit to 400K
        ->addValidator('Extension', false, 'pdf');
    $subform->addElement($proof);

    $lang = new Zend_Form_Element_Select('Language');
    $lang->setLabel('Language')->setRequired(TRUE);
    $subform->addElement($lang);

    $this->addSubForm($subform,'importForm');

    $submit = new  Zend_Form_Element_Submit('submitForm');
    $submit->setLabel('Save');
    $this->addElement($submit);


    $this->setAction('/cred/save')
        ->setMethod('post')
        ->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
  }

}

When I call $form->isValid($_POST), it validates both the parent form and the sub-form and returns errors when the subform's required elements are empty even when the sub-form itself is not required.

Other than overloading the isValid() function, is there any way to validate only the parent form?

1

There are 1 best solutions below

1
On

If you look into the source code the isValid() method of Zend_Form you see that there is no explicit mechanism that prevents the execution of the validators on the subforms (line 2273 ff).

Anyway, If I understand your requirement "The sub-form will not always be filled but when any of its elements are filled, they should all be filled." correctly then I think your problem does not necessarily have something to do with subforms per se but rather with conditional validation. This can be solved pretty easy with a custom validator: How to validate either Zend_Form_Element_File or Zend_Form_Element_Text are not empty.

Just keep in mind that the elements in $context contain only the subform elements.