ashurexm
ashurexm

Reputation: 6335

Appending or Prepending HTML Tags to Zend Form Element

For the purposes of styling I have the need to put an opening <div> at the beginning of one element, and a closing </div> tag at the end of another. Looking over the docs for HtmlDecorator I can't seem to figure out how to get it right, or if this is even the right decorator to use. It seems wasteful to have to create my own decorator simply to achieve this.

Upvotes: 5

Views: 9487

Answers (2)

David Weinraub
David Weinraub

Reputation: 14184

Sounds like you could use a display group with an HtmlTag decorator.

Something like:

$form = new Zend_Form();

$form->addElement('text', 'elt1', array(
    'label' => 'Element 1',
));
$form->addElement('text', 'elt2', array(
    'label' => 'Element 2',
));

$form->addDisplayGroup(array('elt1', 'elt2'), 'myDisplayGroup');
$group = $form->getDisplayGroup('myDisplayGroup');

$group->setDecorators(array(
   'FormElements',
   array('HtmlTag', array('tag' => 'div', 'class' => 'myClass'))
));

This produces HTML as follows:

<form method="post" action="" enctype="application/x-www-form-urlencoded">
    <dl class="zend_form">
        <div class="myClass">
            <dt id="elt1-label"><label class="optional" for="elt1">Element 1</label></dt>
            <dd id="elt1-element"><input type="text" value="" id="elt1" name="elt1"></dd>
            <dt id="elt2-label"><label class="optional" for="elt2">Element 2</label></dt>
            <dd id="elt2-element"><input type="text" value="" id="elt2" name="elt2"></dd>
        </div>
    </dl>
</form>

Of course, jamming a <div> tag inside all that <dl>, <dt> and <dd> madness produces invalid markup, but I presume that you are specifying different decorators for your form elements so that the <div> wrap you desire will ultimately be valid.

Also notable for more general markup manipulations is the AnyMarkup Decorator.

Upvotes: 7

Maxence
Maxence

Reputation: 13306

On the element where you want to add a <div>, add this decorator :

array(
    array('openDiv' =>'HtmlTag'),
    array('tag' => 'div', 'openOnly' => true)
)

On the element where you want to add a </div>, add this decorator :

array(
    array('closeDiv' =>'HtmlTag'),
    array('tag' => 'div', 'closeOnly' => true)
)

Upvotes: 16

Related Questions