自定义视图助手中的验证

时间:2014-10-19 15:10:58

标签: php zend-framework

注意:Zend Framework 1.12

我试图添加对某些HTML5表单元素的支持。我在网上找到了一些片段来启动我。现在我需要为新的" required"添加支持。属性:

<input type="email" name="email" id="email" required>

理想情况下,我应该可以使用

$element->setRequired(true);

它会添加适当的标签。但我无法解决如何从帮助程序中访问此设置的问题。所以我不得不将其添加到表单中

$element->setAttrib('required', '');

那不理想。如何让setRequired自动添加标签?这是迄今为止的帮助程序代码:

<?php

class Application_View_Helper_FormEmail extends Zend_View_Helper_FormElement {

    public function formEmail($name, $value = null, $attribs = null) {
        $info = $this->_getInfo($name, $value, $attribs);
        extract($info);
        $disabled = '';
        if ($disable) {
            // disabled
            $disabled = ' disabled="disabled"';
        }

        $xhtml = '<input type="email"'
                . ' name="' . $this->view->escape($name) . '"'
                . ' id="' . $this->view->escape($id) . '"'
                . ' value="' . $this->view->escape($value) . '"'
                . $disabled
                . $this->_htmlAttribs($attribs)
                . $this->getClosingBracket();

        return $xhtml;
    }

}

1 个答案:

答案 0 :(得分:1)

啊,没关系,我设法解决了!只需要覆盖表单元素中的setRequired方法,并将setAttrib调用添加到它:

class Application_Form_Element_Email extends Zend_Form_Element_Xhtml {

    /**
     * Default form view helper to use for rendering
     * @var string
     */
    public $helper = 'formEmail';

    public function __construct($spec, $options = null) {
        parent::__construct($spec, $options);
        $this->addValidator('Email');
    }

    public function setRequired($flag = true) {
        parent::setRequired($flag);
        parent::setAttrib('required', '');
        return $this;
    }

}