Appending or Prepending HTML Tags to Zend Form Element
Asked Answered
N

2

5

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.

Natividad answered 3/10, 2010 at 1:29 Comment(0)
P
16

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)
)
Pharyngeal answered 4/10, 2010 at 15:8 Comment(1)
This is exactly what I'm looking for in this particular case, thank you!Natividad
D
7

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.

Desideratum answered 3/10, 2010 at 6:11 Comment(1)
DavidW, Thank you for the great example. I totally forgot about using display groups.Natividad

© 2022 - 2024 — McMap. All rights reserved.