1

我有一个 Zend_Form,它的子表单仅在某些情况下才需要。父表单和子表单都有必填字段。子表单不会总是被填充,但是当它的任何元素被填充时,它们都应该被填充。

<?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);
  }

}

当我调用时$form->isValid($_POST),它会验证父表单和子表单,并在子表单的必需元素为空时返回错误,即使不需要子表单本身也是如此。

除了重载isValid()函数之外,有没有办法只验证父表单?

4

1 回答 1

0

如果您查看Zend_Form 的 isValid() 方法的源代码,您会发现没有显式机制阻止验证器在子表单上的执行(第 2273 行 ff)。

无论如何,如果我理解你的要求“子表单不会总是被填充,但是当它的任何元素被填充时,它们都应该被填充。 ”那么我认为你的问题不一定与子表单本身有关而是有条件的验证。这可以通过自定义验证器轻松解决:如何验证 Zend_Form_Element_File 或 Zend_Form_Element_Text 是否为空。

请记住,其中的元素$context仅包含子表单元素。

于 2014-01-05T15:50:31.720 回答