Zend Form Decorators Error in Table

2019-05-19 17:41发布

问题:

I am using the next decorators for my input. I want to make this as table.

$this->setDecorators(array('ViewHelper','Errors',
           array(array('data'=>'HtmlTag'), array('tag' => 'td')),
           array('Label', array('tag' => 'td')),
           array(array('row'=>'HtmlTag'),array('tag'=>'tr'))
   ));

But after form validation Errors showing not in td. How can I do this? I want to make the next makeup:

<table>
   <tr>
      <td>Lable</td>
      <td>Input</td>
      <td>Error</td>
   </tr>
</table>

回答1:

$this->setDecorators(
   array(
      'ViewHelper',
      array(
         array(
            'data'=>'HtmlTag'
         ),
         array(
            'tag' => 'td'
         )
      ),
      array(
         'Label', 
         array(
            'tag' => 'td'
         )
      ),
      array(
         'Errors', 
         array(
            'tag' => 'td'
         )
      ),
      array(
         array(
            'row'=>'HtmlTag'
         ),
         array(
            'tag'=>'tr'
         )
      )
   )
);


回答2:

You can write your own Decorator similar to:

class My_Form_Decorator_ErrorsHtmlTag 
    extends Zend_Form_Decorator_Label
{
    protected $_placement = 'APPEND';

    public function render($content) {
        $element = $this->getElement();
        $view = $element->getView();
        if (null === $view) {
            return $content;
        }

        $separator = $this->getSeparator();
        $placement = $this->getPlacement();
        $tag = $this->getTag();
        $tagClass = $this->getTagClass();
        $id = $element->getId();

        $errors = $element->getMessages();
        if (!empty($errors)) {
            $errors = $view->formErrors($errors, $this->getOptions());
        } else {
            $errors = '';
        }

        if (null !== $tag) {
            $decorator = new Zend_Form_Decorator_HtmlTag();
            if (null !== $tagClass) {
                $decorator->setOptions(array(
                    'tag' => $tag,
                    'id' => $id . '-errors',
                    'class' => $tagClass));
            } else {
                $decorator->setOptions(array(
                    'tag' => $tag,
                    'id' => $id . '-errors'));
            }
            $errors = $decorator->render($errors);
        }

        switch ($placement) {
            case self::APPEND:
                return $content . $separator . $errors;
            case self::PREPEND:
                return $errors . $separator . $content;
        }
    }
}

and then use it as (in class derived from Zend_Form):

$this->addPrefixPath('My_Form_Decorator', 'My/Form/Decorator/', 'decorator');    
$element->setDecorators(array(
    'ViewHelper',
    array(array('td' => 'HtmlTag'), array('tag' => 'td')),
    array('Label', array('tag' => 'td')),
    array('ErrorsHtmlTag', array('tag' => 'td')),
    array(array('tr' => 'HtmlTag'), array('tag' => 'tr'))));