Search code examples
formszend-framework2

Add div around input field in ZF2 form


I am creating a form with Zend Framework 2. I'm using Form class to define form elements like this:

class PropertyForm extends Form
{
    public function __construct($name=null)
    {
    ...

        $this->add(array(
            'name' => 'zip',
            'type' => 'Text',
            'required' => false,
            'options' => array(
                'label' => 'Zip Code',
            ),
            'attributes' => array(
                'id' => 'zip',
                'class' => 'form-control',
            ),
        )); 

    ...
    }
}

And in view I display this form element with the following code:

<div class="form-group"><?php echo $this->formRow($form->get('zip')); ?></div>

This generates the following HTML output:

<div class="form-group">
    <label for="zip">Zip Code</label>
    <input type="text" name="zip" id="zip" class="form-control" value="">
</div>

What I want to achieve is to have <div class="my-class"> around the input field as well. So the desired HTML output would be:

<div class="form-group">
    <label for="zip">Zip Code</label>
    <div class="my-class">
        <input type="text" name="zip" id="zip" class="form-control" value="">
    </div>
</div>

How can I achieve that?


Solution

  • You could get label and the element itself with two different calls:

    For label:

    <?php echo $this->formLabel($yourForm->get('your_element')); ?>
    

    For the elements:

    <?php echo $this->formSelect($yourForm->get('your_element_select')); ?>
    <?php echo $this->formText($yourForm->get('your_element_text')); ?>
    <?php echo $this->formRadio($yourForm->get('your_element_radio')); ?>
    

    So, for you example, it would be something like:

    <div class="form-group">
        <?php echo $this->formLabel($form->get('zip')); ?>
        <div class="my-class">
            <?php echo $this->formText($form->get('zip')); ?>
        </div>
    </div>