3

I want to create a form to add a user:

$builder->add('firstname', 'text', array(
                    'required' => 'required'
                ))
                ->add('middlename')
                ->add('lastname')
                ->add('email', 'email')
                ->add('isActive');

but I want to add also one group. I have a entity "Group" and a form "GroupType". But how to add a choice with all my groups to select one or multiple?

I tried:

->add('groups', 'choice' )

but getting this error:

Notice: Object of class Doctrine\Common\Collections\ArrayCollection could not be converted to int in /vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php line 457 

How to fix this?

Mitchel Verschoof
  • 1,543
  • 4
  • 20
  • 38

1 Answers1

10

To create a choice field populated with all the Group objects from the database, use an 'entity' field. To enable multiple selection (1+ choices) use the 'multiple' option. For example:

$builder->add('groups', 'entity', array(
    'class' => 'YourBundle:Group',
    'property' => 'name',
    'multiple' => true,
));

The value of the 'property' option determines which Group field is displayed. If you need to order the objects in the choice element or display a subset of the objects, use the 'query_builder' option to load the choice using a custom query. For example:

use Doctrine\ORM\EntityRepository;
// ...

$builder->add('groups', 'entity', array(
    'class' => 'YourBundle:Group',
    'property' => 'name',
    'multiple' => true,
    'query_builder' => function(EntityRepository $er) {
        return $er->createQueryBuilder('g')
                  ->orderBy('g.name', 'ASC');
    },
));

See entity Field Type in the Symfony2 documentation.

redbirdo
  • 4,937
  • 1
  • 30
  • 34
  • If you got an error like: `The property "groups" in class "AppBundle\Entity\User" can be defined with the methods "addGroup()", "removeGroup()" but the new value must be an array or an instance of \Traversable, "AppBundle\Entity\Group" given.` You must try to add Getter and setter in User class – Franckentien Jun 26 '19 at 08:31