Php – zend form for multicheckbox remove input from labels

htmlPHPzend-formzend-form-elementzend-framework

I am using zend_form (part of Zend Framwork) to create a form and found when I add a set of checkboxes using Zend_Form's multicheckbox element (Zend_Form_Element_MultiCheckbox) the code that is outputted like so:

<label for="subjects-maths">
    <input type="checkbox" value="maths" id="subjects-maths" name="subjects[]">
    Maths
</label>
<label for="subjects-english">
    <input type="checkbox" value="maths" id="subjects-english" name="subjects[]">
    English    
</label>

I.e. the input is inside the label. Whereas the code is technically ok it is against good practice as far as the W3c see it and is also not the way I want it as it makes styling harder. What I want is the following:

<div>
    <label for="subjects-maths">        
        Maths
    </label>
    <input type="checkbox" value="maths" id="subjects-maths" name="subjects[]">
</div>
<div>
    <label for="subjects-english">            
        English    
    </label>
    <input type="checkbox" value="maths" id="subjects-english" name="subjects[]">
</div>

Therefore how do I move the checkbox input out of the label and how do I surround each option in divs. I have looked at many pages on the internet of so called solutions but none work on multicheckboxes as it only targets surrounding labels (i.e the one that would say subjects in this example) not the actual options labels and inputs.

Please help.

Thanks
Paul

Best Answer

The decorator Zend_Form_Decorator_ViewHelper is by default using the view helper Zend_View_Helper_FormMultiCheckbox to render your multicheckbox element. That view helper is extended from Zend_View_Helper_FormRadio which for some reason is hard-coded to put <label> tags around the <input> tag.

You'll need to write your own view helper that copies most of the code from Zend_View_Helper_FormRadio::formRadio() but writes the HTML without <label> tags around the element. Here's a snippet from another answer that shows the modification you might want to make.

Your custom helper should be named Some_Prefix_Helper_FormMultiCheckbox but without knowing how your app is structured it's hard to say exactly what that Some_Prefix should be or how you would make sure to load it instead of Zend_View_Helper_FormMultiCheckbox. Check out the documentation on loading plugins for some tips.