Symfony 2.6 are checked by default

How can I set the default checkboxes based on data from the database?
Now my form looks like this:

      ...
      ->add(
        "role", "entity", [
          "class"    => "AppDefaultBundle:OptionRole",
          "required" => false,
          "label"    => "Roles for user: ",
          "property" => "name",
          "expanded" => true,
          "multiple" => true
        ]
      )
      ...

      

And I want to select the default values ​​for these checkboxes based on data from another table.

+3


source to share


1 answer


You should probably add a select property: http://symfony.com/doc/current/reference/forms/types/choice.html#choices

In your case, you should have an array with all OptionRoles relevant to the (User?) Object you are working on (the one you create for the form).

Assuming the Doctrine model knows its OptionRoles (most likely a ManyToMany association), the form should automatically check users' OptionPoles checkboxes.

Here's one example:



[ 
    'label' => 'Select Modules',
    'class' => 'Foo\BarBundle\Entity\Module',
    'choices' => $this->availableModules(),
    'property' => 'name',
    'multiple' => true,
    'expanded' => true
]

      

...

public function availableModules()
{
    return $this->get('doctrine')
    ->getManager()
    ->getRepository('Foo\BarBundle\Entity\Module')
    ->findAll();
}

      

+2


source







All Articles