ZendFramework:验证失败后更改表单元素

时间:2011-11-23 18:30:24

标签: forms zend-framework

所以我按以下方式设置表格:

在我的表单目录中:

Address.php

class Address extends Zend_Form{
    // Creates an address input box including address/country/state/zip
    // The states is created as a drop down menu 
    public function init() {
         // relevant code to question
         $this->addElements(array(
            array('select', $names['state'], array(
                'label'        => "State",
                'class'        => 'state',
                'multiOptions' => array('' => '') + AddressHelper::stateList(),
                'required'     => $this->_required,
            )),
         ));
    }
}

MyForm.php:

class MyForm extends Zend_Form {
  public function init() {
    //set-up some general form info 

    // this is the relevant part for my question
    // $opt is a predefined variable
    $this->addSubForms(array(
            'info' => new SubForm($opts),
            'mailing' => new Address($opts + array(
                'legend' => 'Address', 
                'isArray' => false, 
                'required' => true,
        )),
    ));  
   }
}

Survey.php

class Survey extends MyForm{
    // initialize parent (MyForm) and add additional info for the Survey form
}

好的,所以在提交调查时,如果验证失败,我需要将地址状态元素从选择更改为输入类型=文本。

所以在我的控制器中,在检查验证的操作下,我有以下内容:

public function createAction(){
     if ($this->_form->isValid($post)) {
        $this->_saveDraft($post, $this->_submissionType);
        $this->addSessionMessage('Submission created!');
        return $this->redirector->gotoRouteAndExit(array(), 'home', true);
     }else{
        /* IMPORTANT */
        // I need to change the Address select field to a text field here!

        $errors[] = 'There was a problem';
        $this->view->assign(compact('form', 'errors', 'submission'));
        $this->_viewRenderer->renderScript('update.phtml');
     }
}

那么,我只是在Address类中创建一个方法,并以某种方式调用它来换出。我只是不确定如何解决这个问题。

1 个答案:

答案 0 :(得分:2)

您将看到使用removeElement()删除select元素,然后使用addElement()将其替换为纯文本版本。

您将遇到的问题是,当验证失败时,select元素将更改为文本元素,并重新显示该表单。现在,重新提交后,您需要在调用isValid()之前再次进行更改,因为表单使用文本输入进行状态而不是选择。所以你需要做两次改变。一旦在重新显示表单之前验证失败,并且在调用isValid()之前一次,但仅在先前失败的提交之前。

现在为什么如果表单验证失败,您希望状态的select元素是文本吗?它不能与select元素一样工作,你只需为它们预先选择正确的状态吗?

编辑:

您使用表单对象来调用add / removeElement。

$removed = $form->getSubForm('mailing')->removeElement('state_select');
$form->getSubForm('mailing')->addElement($text_state_element);

该调用应该可以从子表单中删除元素。

没有子表单,只是:

$form->removeElement('username');
$form->addElement($someNewElement);

如果您需要从表单中获取元素以进行更改(例如,删除/添加验证程序,更改说明,设置值),您可以以类似的方式使用getElement()

$el = $form->getElement('username');
$el->addValidator($something)
   ->setLabel('Username:');

希望有所帮助。