ZF1:将输入类型添加为标记包装输入字段的类

时间:2013-07-01 21:08:44

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

有没有办法将input-element的类型添加到包装标签上的class属性? 在下面的示例代码中,它可能是'Div'装饰器,它已经具有'element'或LI-tag类。

(我已经省略了一些代码)

class My_Form extends Zend_Form
{
  public function loadDefaultDecorators($disableLoadDefaultDecorators = false)

    //Set the decorators we need:
    $this->setElementDecorators(array(
        'ViewHelper',
        'Errors',
        array('Description', array('tag' => 'p', 'class' => 'description', 'escape' => false)),
        array('decorator' => array('Div' => 'HtmlTag'), 'options' => array('tag' => 'div', 'class' => 'element')),
        array('Label', array('escape' => false)),        
        array('decorator' => array('Li' => 'HtmlTag'), 'options' => array('tag' => 'li')),        
    ));
  }
}

如果可以创建My_Form_Element,则自动从中扩展所有Zend_Form_Element_XXX。

我想以这样的标记结束

<form>
  <ul>
    <li>
      <label for="contactForm-contact_subject" class="optional">Regarding:</label>
      <div class="element form-input-text"><input type="text" name="contactForm[contact_subject]" id="contactForm-contact_subject" value="" /></div>
    </li>
    <li>
      <label for="contactForm-contact_message" class="required">Message:</label>
      <div class="element form-textarea"><textarea name="contactForm[contact_message]" id="contactForm-contact_message" rows="24" cols="80"></textarea></div>
    </li>
    <li>
      <div class="element form-input-submit"><input type="submit" name="contactForm[form_contact_submit]" id="contactForm-form_contact_submit" value="form_contact_submit" /></div>
    </li>
  </ul>
</form>

1 个答案:

答案 0 :(得分:1)

只需覆盖渲染方法:

class My_Form extends Zend_Form
{   
    public function loadDefaultDecorators($disableLoadDefaultDecorators = false)
    {
        //Set the decorators we need:
        $this->setElementDecorators(array(
            'ViewHelper',
            'Errors',
            array('Description', array('tag' => 'p', 'class' => 'description', 'escape' => false)),
            array('decorator' => array('Div' => 'HtmlTag'), 'options' => array('tag' => 'div', 'class' => 'element')),
            array('Label', array('escape' => false)),        
            array('decorator' => array('Li' => 'HtmlTag'), 'options' => array('tag' => 'li')),        
        ));
    }

    public function render(Zend_View_Interface $view = null)
    {
        /* @var $element Zend_Form_Element */
        foreach ($this->getElements() as $element) {
            $type = end(explode('_', $element->getType()));
            $element->getDecorator('Div')->setOption('class', 
                sprintf('%s form-%s', 'element', strtolower($type)));
        }

        return parent::render($view);
    }    
}