简体   繁体   中英

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", ie 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://symfony.com/doc/current/reference/forms/types/collection.html [2] http://symfony.com/doc/current/reference/forms/types/checkbox.html

You will need a second FormType.

The first form which you are calling should look something like this:

$builder
  ->add('zones', 'collection',
    array(
      'type' => new FormDataType(),
      'options'  => array(
         .....
      )
    )
  )

And then the second form should look like this:

class FormDataType extends AbstractType  {
 ...
   $builder
      ->add('checkBox1', 'checkbox', ...)
      ->add('checkBox2', 'checkbox', ...)
      ....
}

I just wrote this, so I can not tell if it will work,... but this is the approach you will have to go, I have already done something like that in one of my projects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM