Dennis
Dennis

Reputation: 8101

How to control individual form element rendering in Zend Form?

Brief

I am using Zend Form library. I want to be able to style or have some control over how radio boxes are constructed. Currently the rendering of the element is "in one row". What I want to do however is render each option on its own line. Library does not seem to provide an easy injection of i.e. <br> tag, which is what I would normally use in my HTML. I need help figuring out how to bend the library to my needs anyway.

Controller

    use Zend\Form\Element;
    use Zend\Form\Form;

    $radio = new Element\Radio('gender');

    $radio->setValueOptions(array(
        '1' => 'Male',
        '2' => 'Female',
        '3' => 'Other',            
    ));
    $radio->setValue(2);

In View

<?=$this->formRadio($this->form->get('gender'));?>

Observe Element Rendered as

* Male * Female * Other

Want Element rendered as

* Male
* Female
* Other

How?

Sample HTML Rendering

<form class='my-form'>
    <table>
        <tr>
            <td>
                <label><input name="gender" type="radio" value="1">Male</label> 
                <label><input name="gender" type="radio" value="2">Female</label>
            </td>
        </tr>
    </table>
</form>

Upvotes: 0

Views: 515

Answers (1)

Peter M. Elias
Peter M. Elias

Reputation: 1194

You can side-step Zend Framework completely and save some page-weight (by not using br tags) by using CSS to solve this problem.

Simply look at the tag or classname of the repeated element being used to render your list items (sounds like it's a radio input) and style it to display vertically instead of horizontally.

An example:

.my-form input[type="radio"] {
    display: block;
}

This will be faster and simpler than custom rendering decorators in Zend.

EDIT: Now that you have provided the exact HTML, here is some refinement.

1) The inputs are nested within the labels, so you will modify the display of the labels instead of the inputs.

.my-form label {
    display: block;
}

2) The rendered form (if this is exact) does not currently have a class name. If the form will never be used more than once on a page than the current ID is fine and you will have to change the selector in the CSS to use ID notation.

#myform label instead of .my-form label

Otherwise, you can use Zend's setAttribute function to add a class name like so.

$form -> setAttribute('class', 'my-form');

Upvotes: 1

Related Questions