1

我已经为电子邮件设置了一个验证器,所以它不能为空。

这是 zend_form 生成的常用表单的标记:

<dt id="email-label"><label class="required" for="email">Email</label></dt>
<dd id="email-element">
   <input type="text" value="" id="email" name="email">
</dd>

当验证失败时,zend_formul class="errors"在 dd中添加一个新的

<dt id="email-label"><label class="required" for="email">Email</label></dt>
<dd id="email-element">
   <input type="text" value="" id="email" name="email">
   <ul class="errors">
      <li>Value is required and can't be empty</li>
   </ul>
</dd>

我怎样才能稍微改变这个默认行为,以便整个dt dd被包裹在一个单一的p或者something我可以添加一个错误类?我的猜测是我需要向 zend_form 指定元素出现错误时的行为方式。

4

1 回答 1

5

您可以创建自己的装饰器来做到这一点,像这样简单::

class My_Decorator_ElementWrapper extends Zend_Form_Decorator_Abstract
{
    public function render($content)
    {
        $class = 'form-element';
        $errors = $this->getElement()->getMessages();
        if (!empty($errors))
            $errors .= ' has-errors';
        return '<div class="'.$class.'">' . $content . '</div>';
    }
}

现在你可以为元素注册这个装饰器:

$element->addPrefixPath('My_Decorator', 'My/Decorator/', 'decorator');
$element->addDecorator('ElementWrapper');

您还可以通过使用来同时为所有元素注册前缀路径$form->addElementPrefixPath()

如果你想为所有元素自动添加这个装饰器(和前缀路径),我建议你扩展 Zend 对应的每个元素(例如 make My_Form_Element_Textthat extends Zend_Form_Element_Text),然后在 init 函数中添加前缀路径,并覆盖loadDefaultDecorators()方法ElementWrapper在装饰器链的末尾添加。例如,这是loadDefaultDecorators()查找的方式Zend_Form_Element_Text

public function loadDefaultDecorators()
{
    if ($this->loadDefaultDecoratorsIsDisabled()) {
        return $this;
    }

    $decorators = $this->getDecorators();
    if (empty($decorators)) {
        $this->addDecorator('ViewHelper')
            ->addDecorator('Errors')
            ->addDecorator('Description', array('tag' => 'p', 'class' => 'description'))
            ->addDecorator('HtmlTag', array('tag' => 'dd',
                                            'id'  => $this->getName() . '-element'))
            ->addDecorator('Label', array('tag' => 'dt'));
    }
    return $this;
}

您只需->addDecorator('ElementWrapper')在链的末尾添加一个。所以要展示一个具体的例子My_Form_Element_Text

class My_Form_Element_Text extends Zend_Form_Element_Text
{
    public function init()
    {
        $this->addPrefixPath('My_Decorator', 'My/Decorator/', 'decorator');
    }

    public function loadDefaultDecorators()
    {
        if ($this->loadDefaultDecoratorsIsDisabled()) {
            return $this;
        }

        $decorators = $this->getDecorators();
        if (empty($decorators)) {
            $this->addDecorator('ViewHelper')
                ->addDecorator('Errors')
                ->addDecorator('Description', array('tag' => 'p', 'class' => 'description'))
                ->addDecorator('HtmlTag', array('tag' => 'dd',
                                                'id'  => $this->getName() . '-element'))
                ->addDecorator('Label', array('tag' => 'dt'))
                ->addDecorator('ElementWrapper');
        }
        return $this;
    }
}
于 2010-10-06T23:09:49.630 回答