Question

I've been Googling this to no avail. I have a multi-checkbox form element in one of my forms. Here's the code I used to create it:

$this->add(array (
    'name' => 'thingyId',
    'type' => 'MultiCheckbox',
    'options' => array (
        'value_options' => $thingyArray,
    )
));

In my view script, I have this:

<?= $this->formRow($form->get('thingyId')); ?>

The form element shows up fine, but all of the checkboxes are on a single line. How do I get it so that each checkbox is on a new line?

Was it helpful?

Solution

If you view this link, you can see that the fourth argument is partial. So, you can use many ways to accomplish the task.

Method 1:

echo $this->formRow($element, null, null, 'template-file');

Now, create a template file named as template-file.phtml to render the element however you like.

//template-file.phtml
<span><?php echo $label; ?></span><br/>
<?php foreach ($element->getValueOptions() as $key => $value): ?>
    <input type="checkbox" name="<?php echo $element->getName() ?>[]" value="<?php echo      $value; ?>">
    <span><?php echo $key; ?></span><br/>
<?php endforeach; ?>

Method 2

Create your own view helper by extending the default helper.

namespace Application\View\Helper;

class MyFormRow extends \Zend\Form\View\Helper\FormRow
{
       /**
        * @var string
        */
       protected $partial = 'template-file';
}

Now, inform our application about our new helper in your module,

namespace Application;

class Module 
{
    public function getViewHelperConfig()
    {
        return array(
            'invokables' => array(
               'myFormRow' => 'Application\View\Helper\MyFormRow'
            )
        );
    }
}

Lastly use the helper:

echo $this->myFormRow($element);

OTHER TIPS

I came across this question when I was having this issue myself. The code that was being used was the following:

<?php
$oMultiCheckboxField = $oForm->get('multicheckboxelement');
echo $this->formMultiCheckbox($oMultiCheckboxField);
?>

The only additional parameter you could pass to the formMultiCheckbox view helper was whether to append or prepend the label.

How I eventually chose to solve this is with the following code:

<?php
$oMultiCheckboxField = $oForm->get('multicheckboxelement');
$oMultiCheckboxViewHelper = new \Zend\Form\View\Helper\FormMultiCheckbox();
$oMultiCheckboxViewHelper->setSeparator('<hr>');
echo $oMultiCheckboxViewHelper->render($oMultiCheckboxField);
?>

From what I recall, ZF1 had the option to set the separator (I clearly remember this at least for radio buttons). Why there isn't a clearer way to do this in ZF2 is a bit puzzling. If there are better ways to do this, I would certainly like to know about it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top