以Zend形式设置描述


Set Description in Zend Form

我在项目中使用Zend Framework。我想在我的表格中添加一个描述/注释,比如

fields marked by * are mandatory

但我没有找到如何向表单添加描述,以及如何将其与decorator一起使用。

如有任何帮助,我们将不胜感激。谢谢

有两个选项:

  • 使用from decorator或
  • 扩展Zend_Form_Element以创建自定义元素

我会选择后者,因为将原始html代码的一部分添加到表单中是非常常见的,不仅在元素之前或之后,而且在元素之间也是如此。

你应该这样做:

class My_Form_Element_Raw extends Zend_Form_Element
{
    protected $raw_html;
    public function setRawHtml($value)
    {
        $this->raw_html = $value;
        return $this;
    }
    public function getRawHtml()
    {
        return $this->raw_html;
    }
    public function render()
    {
        // you can use decorators here yourself if you want, or wrap html in container tags
        return $this->raw_html;
    }
}
$form = new Zend_Form();
// add elements
$form->addElement(
    new My_Form_Element_Raw(
        'my_raw_element', 
        array('raw_html' => '<p class="highlight">fields marked by * are mandatory</p>')
    )
);
echo $form->render();

当扩展Zend_Form_Element时,您不需要覆盖setOption/sgetOption/s方法。Zend内部使用set*get*

向表单添加额外文本的最简单方法是向页面视图添加适当的html:

<div>
    <h4>fields marked by * are mandatory</h>
    <?php echo $this->form ?>
</div>

或者使用viewScript装饰器来控制整个表单体验:

<article class="login">
    <form action="<?php echo $this->element->getAction() ?>"
          method="<?php echo $this->element->getMethod() ?>">
        <table>
            <tr>
                <th>Login</th>
            </tr>
            <tr>fields marked by * are mandatory</tr>
            <tr>
                <td><?php echo $this->element->name->renderViewHelper() ?></td>
            </tr>
            <tr>
                <td><?php echo $this->element->password->renderViewHelper() ?></td>
            </tr>
            <tr>
                <td><?php echo $this->element->submit ?></td>
            </tr>
        </table>
    </form>
</article>

但是,您可以使用$form->setDescription()将描述添加到表单中,然后使用echo $this->form->getDescription()呈现该描述。最好将这些方法与set和getTag()一起在元素级别使用,而不是在表单级别使用。

为了提供星号线索,我只使用css:

dt label.required:before {
    content: "* ";
    color: #ff0000;
}

我相信,如果你愿意,你可以使用css显示任何你想要的注释。

 class FormDecorators {
    public static $simpleElementDecorators = array(
        array('ViewHelper'),
        array('Label', array('tag' => 'span', 'escape' => false, 'requiredPrefix' => '<span class="required">* </span>')),
        array('Description', array('tag' => 'div', 'class' => 'desc-item')),
        array('Errors', array('class' => 'errors')),
        array('HtmlTag', array('tag' => 'div', 'class' => 'form-item'))
    );
    }

这些是我通常使用的元素的装饰符,它们包含带*的前缀和描述装饰符。

然后使用代码:

$element->setDescription('fields marked by * are mandatory');

将描述添加到一个元素中,之后你可以将描述样式设置为出现在底部的某个地方,我希望这会有所帮助,祝你今天愉快。