Zend_Form中的验证取决于元素/字段值?

时间:2012-07-31 11:39:33

标签: php zend-framework zend-form zend-validate

让我们想象一下,我们有形式问:“你是Mr.Mrs先生吗?” 根据答案价值,我们将实施进一步的验证。

例如, 先生>验证最喜欢的汽车模型 太太>验证最喜欢的花

覆盖isValid功能可以吗? 也许是一些最佳实践的例子?

1 个答案:

答案 0 :(得分:1)

我会编写自定义验证程序并使用提供的$context变量。

一个简短的例子

<强>控制器

class MyController extends Zend_Controller_Action {
    public function indexAction() {
        $form = new Application_Form_Gender();
        $this->view->form = $form;

        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                /*...*/
            }
        }
    }
}

<强>表格

class Application_Form_Gender extends Zend_Form {

    public function init()
    {
        $this->addElement('radio', 'radio1', array('multiOptions' => array('m' => 'male', 'w' => 'female')));
        $this->getElement('radio1')->isRequired(true);
        $this->getElement('radio1')->setAllowEmpty(false);

        $this->addElement('text', 'textm', array('label' => 'If you are male enter something here');
        $this->getElement('textm')->setAllowEmpty(false)->addValidator(new MyValidator('m'));

        $this->addElement('text', 'textf', array('label' => 'If you are female enter something here'));     
        $this->getElement('textf')->setAllowEmpty(false)->addValidator(new MyValidator('f'));

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

<强>验证

class MyValidator extends Zend_Validate_Abstract {
    const ERROR = 'error';
    protected $_gender;
    protected $_messageTemplates = array(
        self::ERROR      => "Your gender is %gender%, so you have to enter something here",
    );
    protected $_messageVariables = array('gender' => '_gender');

    function __construct($gender) {
        $this->_gender = $gender;
    }

    function isValid( $value, $context = null ) {
        if (!isset($context['radio1'])) {
            return true;
        }
        if ($context['radio1'] != $this->_gender) {
            return true;
        }
        if (empty($context[sprintf('text%s', $this->_gender)])) {
            $this->_error(self::ERROR);
            return false;
        }
        return true;
    }
}

正如您在此示例中所看到的,$form->isValid()中提供的所有数据都可通过$context变量获取,您可以执行此类检查。