Using multiple dynamic checkboxes in zend form

The code snippets in this article will show you how to manage an unknown number of checkboxes (e.g. a list from a database) in Zend Framework 2 using Zend Form. The snippets should supplement your code, if you're not familiar with using Zend Form or it's elements please check the Introduction to Zend Form and Zend Form Elements in the documentation first.

In this example form, I'm setting up roles that will have resources assigned to them. The resources are passed into the construct, which will be an array of ids and values.

Let's start with the form:

namespace YourModule\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;

class RoleForm extends Form implements InputFilterProviderInterface
    public function __construct( $resources )
            'type' => 'Zend\Form\Element\MultiCheckbox',
            'name' => 'resources',
            'options' => array(
                'label' => 'Please choose the resources for this role',
                'value_options' => $resources,

And here's how we would instantiate and populate the form (in practice the resources would be pulled from a database, for demonstration purposes I have a dummy array):

$resources = array( 1 => 'this', 2 => 'that', 3 => 'other' );
$roleForm = new Form\RoleForm( $resources );

$resourcesChecked = array(1,2); $roleForm->populate( array( 'resources' => $resourcesChecked ) );

Now you can echo the form row in your view, and you should see the appropriate checkboxes are selected:

echo $this->formRow($roleForm->get('resources'));
Sign Up

NEXT: Getting started with Zend 2

This article provides you with an introduction to Zend 2, the changes from Zend 1 and a step-by-step tutorial on creating a hello world module.

comments powered by Disqus

Popular Tags

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.