Search code examples
phphtmlzend-frameworkzend-framework2zend-form

How to customize checkbox group in Zend framework-2 form?


Actually I can not understand, how zend framework 2 generate HTML for a form element. For example,

$others = new Element\MultiCheckbox('others');
$others->setLabel('Others')
        ->setAttribute('name', 'others');
$others->setValueOptions(array(
    '1' => 'Contacts',
    '2' => 'Who viewd my profile'
));

This code generates -

<label><input type="checkbox" value="1" name="others[]">Contacts</label>
<label><input type="checkbox" value="2" name="others[]">Who viewd my profile</label>

But I need to make the HTML as follows -

<input type="checkbox" value="1" name="others[]"><label>Contacts</label>
<input type="checkbox" value="2" name="others[]"><label>Who viewd my profile</label>

So If I want to change the generated HTML, How can I do it?


Solution

  • For this kind of Feature you would need to overwrite Zend\Form\View\Helper\MultiCheckbox or to be more precise the renderOptions() function of it.

    You'd then let the ViewHelperManager know that $this->formMultiCheckbox() should invoke your very own ViewHelper to get the desired result.

    However i want to mention that what you're trying to do is HIGHLY discouraged. Users should absolutely be able to click the label! IF you're going to change the markup, at least do it like this:

    <input type="checkbox" value="1" name="others[]" id="cbOthers1"><label for="cbOthers2">Foo</label>
    <input type="checkbox" value="2" name="others[]" id="cbOthers1"><label for="cbOthers2">Bar</label>
    

    Never forget about the usability of your application! Another hint: having the CB inside the label automatically enables you a much wider audience as far as browser support with styling is concerned! Then again though, all up to you. You will have to write yourself your own ViewHelper anyways.

    PS: your ViewHelper would be pretty easy, you'll only need to overwrite those lines to the following:

      switch ($labelPosition) {
         case self::LABEL_PREPEND:
            $template  = $labelOpen . '%s'. $labelClose .'%s';
            $markup    = sprintf($template, $label, $input);
         break;
         case self::LABEL_APPEND:
         default:
            $template  = '%s' . $labelOpen . '%s'. $labelClose;
            $markup    = sprintf($template, $input, $label);
          break;
     }