Zend Framework 2 - Form Element Decorators

Ron picture Ron · Dec 18, 2012 · Viewed 16.6k times · Source

I want to force the Zend form into Twitter Bootstrap style. I currently iterate through the form fields and write the form info into my bootstrap div construction.

I saw in Zend Framework 1(!) that there is a way to do this within a decorator. But for some reason the doc for version 2 doesn't cover this point...

I'd like to do something like this:

protected $_format = '<label for="%s">%s</label>'
             . '<input id="%s" name="%s" type="text" value="%s"/>';

public function render($content)
{
    $element = $this->getElement();
    $name    = htmlentities($element->getFullyQualifiedName());
    $label   = htmlentities($element->getLabel());
    $id      = htmlentities($element->getId());
    $value   = htmlentities($element->getValue());

    $markup  = sprintf($this->_format, $name, $label, $id, $name, $value);
    return $markup;
}

Any ideas?

Answer

Ron picture Ron · Jan 9, 2013

I'm using partials now. I'm iterating over the attributes, build a few exceptions for eg CSRF and Submit... This works pretty smooth:

View

echo $this->partial('partial/form-partial', array(
'form' => $this->form,
'url' =>  $this->url('whatever', array('action' => 'add')))); ?>

Partial

<?php
$form = $this->form;
$form->setAttribute ( 'action', $this->url () );
$form->prepare ();

echo $this->form ()->openTag ( $form );
foreach ( $form as $element ) :
?>
    <div
        class="control-group <?php if($this->formElementErrors($element)) echo "error" ?>">
        <label class="control-label"><?php echo $element->getLabel() ?></label>
        <div class="controls">
                <?php echo $this->formElement ( $element );
                    if ($this->formElementErrors ( $element ))
                ?>
            <span class="help-inline"><?php echo $this->formElementErrors($element) ?></span>
        </div>
    </div>
<?php
endforeach;
echo $this->form ()->closeTag ( $form );
?>

The exceptions are left out for clearity's sake...