TwystO
TwystO

Reputation: 2562

Wrap a checkbox in a label using ZF decorators

I encountered some issues with Zend Decorators (ZF1) in wrapping a checkbox into a label. In my Form I have something very simple like that :

$remember = new Zend_Form_Element_Checkbox('remember');
$remember
    ->setLabel('Remember me');

And in my decorators class :

$checkboxDecorator = array(
    'ViewHelper',
    'Errors',
    'Label',
    array('HtmlTag', array('tag' => 'div', 'class' => 'controls')),
    array('decorator' => array('Holder' => 'HtmlTag'), 'options' => array('tag' => 'div', 'class' => 'control-group')),

);

$this->setDefaultElementsDecorators($this->_checkboxElement, $checkboxDecorator);

The source code obtained is the following :

<div class="control-group">
    <div class="controls">
        <label for="remember" class="optional">Remember me</label>
        <input type="hidden" name="remember" value="0">
        <input type="checkbox" name="remember" id="remember" value="1">
    </div>
</div>

And what I want is :

<div class="control-group">
    <div class="controls">
    <label for="remember" class="optional">
        <input type="hidden" name="remember" value="0">
        <input type="checkbox" name="remember" id="remember" value="1">
        Remember me
        </label>
    </div>
</div>

All workarounds I've tested have failed, please help me :P

Upvotes: 4

Views: 1117

Answers (1)

Kevin Nagurski
Kevin Nagurski

Reputation: 1889

Easiest option is to create a new custom decorator...

class App_Form_Decorator_MyLabel
    extends Zend_Form_Decorator_Abstract
{
    public function render($content)
    {
        $el    = $this->getElement();
        $id    = htmlentities($el->getId());
        $label = htmlentities($el->getLabel());

        return '<label for="' . $id . '">' . $content . ' ' . $label . '</label>';
    }
}

Then your $checkboxDecorator becomes:

$checkboxDecorator = array(
    'ViewHelper',
    'MyLabel', // Your new class
    'Errors',
    array('HtmlTag', array('tag' => 'div', 'class' => 'controls')),
    array(
        'decorator' => array('Holder' => 'HtmlTag'),
        'options'   => array(
            'tag'   => 'div',
            'class' => 'control-group'
        )
    )
);

Upvotes: 0

Related Questions