【问题标题】:Zend_Form Over ridding default decoratorsZend_Form 重写默认装饰器
【发布时间】:2009-12-07 11:28:13
【问题描述】:

我在使用 Zend_Form 摆脱默认的装饰器集时遇到了麻烦。

我正在尝试扩展 Zend_Form 以实现不同的装饰器样式。

class CRM_Form extends Zend_Form
{
 public function init()
 {  
  $this->setDisableLoadDefaultDecorators(true);

  $this->addDecorator('FormElements')
->addDecorator('Form');

  $this->setElementDecorators(array(
  'ViewHelper',
  'Label',
 'Errors',
   new Zend_Form_Decorator_HtmlTag(array('tag' => 'p'))
  ));
 }
}

当我尝试像这样使用这个类时:

$form = new CRM_Form();
$form->setAction('/')->setMethod('post'); 
$id = $form->createElement('text','id')->setLabel('ID:');
$form->addElement($id);

使用旧的装饰器(定义列表)而不是我的段落样式。

如果我在 CRM_Form 类的 init() 方法中添加元素(),它们会使用我设置的样式。

如何强制使用该类创建的所有元素使用我的默认样式?

【问题讨论】:

    标签: php zend-framework zend-form


    【解决方案1】:

    当您在 init 中调用 setElementDecorators 时,您没有任何要装饰的元素,因此没有任何反应。相反,您可以覆盖 Zend_Form::createElement 函数,它将执行以下操作:

    1. 如果选项数组包含装饰器列表,则直接传递而无需更改。
    2. 如果选项没有,请添加默认值。

    ..

    // not tested
    public function createElement($type, $name, $options = null)
    {
      if ( !is_array($options) ) {
        $options = array();
      }
      if ( !isset($options['decorators']) ) {
        $options['decorators'] = array(
          'ViewHelper','Label','Errors',
          new Zend_Form_Decorator_HtmlTag(array('tag' => 'p'))
        );
        // I'd make this array a protected class member
      }
    
      return parent::createElement($type, $name, $options);
    }
    

    【讨论】:

      【解决方案2】:

      默认情况下,如果您使用$form->addElement('type', 'name', array('options'=>'example')); 格式添加元素,Zend_Form 将使用您在setElementDecorators 中设置的装饰器。

      如果您自己创建元素,然后将它们传递给$form->addElement() 函数,它不会自动设置装饰器。

      您可以轻松地覆盖该函数,以在已通过在表单中​​执行以下操作创建的元素上设置装饰器:

      public function addElement($element, $name = null, $options = null)
      {
        if ($element instanceOf Zend_Form_Element) {
          $element->setDecorators($this->_elementDecortors);
        }
        return parent::addElement($element, $name, $options);
      }
      

      【讨论】:

        【解决方案3】:

        Zend Form 正在装饰元素你添加它们之后。所以创建一个类似“addAndDecorte”的方法:

        public function addAndDecorate($element) 
        {
           $this->addElement($element);
        
           // do your decorating stuff..
        }
        

        【讨论】:

        • 感谢您最后指出的正确方向,我重新实现了 createElement() 方法并为其添加了装饰器选项。
        猜你喜欢
        • 1970-01-01
        • 2011-06-17
        • 2012-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多