Symfony 2 Form Create user and add Group

2019-05-28 00:41发布

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?

1条回答
何必那么认真
2楼-- · 2019-05-28 01:25

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.

查看更多
登录 后发表回答