【问题标题】:Text around element in Zend_FormZend_Form 中元素周围的文本
【发布时间】:2012-03-09 09:19:14
【问题描述】:

所以我创建了一个简单的 Zend_Form,我想以这种方式显示其中一个元素:

Label:      text [input] text2

我已经使用 LabelDecorator 成功添加标签,我什至可以使用 DescriptionDecorator 添加 text1 或 text2 作为描述,但我不知道如何添加它们。我知道我可以添加两个 DescriptionDecorator,一个前置一个附加,但是它们都有相同的内容。

【问题讨论】:

  • 给我们看一些代码?并查看 Zend_Form 视图助手,然后您可以输出任何您喜欢的表单。
  • 我不知道应该显示什么代码...就像$element = $form->getElement('name'); 一样,表单本身是在 ini 文件中定义的。 Element 只是一个简单的文本输入。 Viewhelper 似乎是某种答案,虽然它不是很灵活(如果我错了,请纠正我,但我认为我必须覆盖我在整个系统中使用的默认 viewhelper)。

标签: zend-framework zend-form zend-form-element zend-decorators


【解决方案1】:

您可以创建自己的装饰器:

class My_Form_Decorator_PlainText extends Zend_Form_Decorator_Abstract
{
    public function render($content)
    {
        return $content . $this->getOption('text');
    }
}

然后多次添加这个装饰器:

$this->addElement($this->createElement('text', 'fieldname')
        ->setLabel('Label')
        ->addPrefixPath('My_Form', 'My/Form/')
        ->setDecorators(array(
            'Label',
            array(array('before'=>'PlainText'), array('text' => 'hello')),
            'ViewHelper',
            array(array('after'=>'PlainText'), array('text' => 'world')),
        )));

【讨论】:

    【解决方案2】:

    我最终创建了一个自定义表单装饰器:

    <?php
    /** Zend_Form_Decorator_Abstract */
    require_once 'Zend/Form/Decorator/Abstract.php';
    
    class Zend_Form_Decorator_Surrounded extends Zend_Form_Decorator_Abstract
    {
        /**
         * Render element
         *
         * @param  string $content
         * @return string
         */
        public function render($content)
        {
            $options   = $this->getOptions();
            if(!isset($options['text'])) return $content;
    
            return sprintf($options['text'], $content);
        }
    }
    ?>
    

    我是这样使用的:

    <?php
    $element->setDecorators(array(
        'ViewHelper', 
        'Errors',
        array('Surrounded', array('text' => 'text1 %s text2')),
        'HtmlTag',
    ));
    ?>
    

    您认为这是一个很好的解决方案,有什么缺点吗?

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 1970-01-01
      相关资源
      最近更新 更多