samedi 31 janvier 2015

Symfony 2 / Twig and a collection of checkboxes

In my application I need to display a group of checkboxes with which the user can indicate certain selections. In my case it refers to "zones", i.e. Zone A, Zone B, Zone C, etc.


The problem I'm running into is how to construct this in my form type class using the FormBuilderInterface provided by the framework.


The documentation refers to a "collection" type [1] which seems what I need but I'm having trouble to connect the checkbox element [2]. The documentation only seems to give an example for a single checkbox but I need it for a group.


This is what I have so far (I've left out the other fields for brevity):



class FormType extends AbstractType {

public function buildForm( FormBuilderInterface $builder, array $options )
{
$builder
->add('zones', 'collection',
array(
'type' => 'checkbox',
'options' => array(
'zone-a' => 'Zone A',
'zone-b' => 'Zone B',
'zone-c' => 'Zone C',
)
)
)
;
}

}


And the data class (form model if you will):



class FormData {

protected $zones = [];

public function __construct( array $zones = NULL )
{
if( ! empty( $zones ) )
{
$this->setZones( $zones );
}
}

public function getZones()
{
return $this->zones;
}

public function setZones( $zones )
{
$this->zones = $zones;
}

}


This is how I render the form element (for now):



{{ form_row(form.zones) }}


However, the above only outputs a label named Zones and nothing else.


How do I correctly render a group/collection of checkboxes in a Symfony 2 / Twig application?


[1] http://ift.tt/1etmweE [2] http://ift.tt/1sffrAN





Aucun commentaire:

Enregistrer un commentaire