Symfony 2:通过手动从ArrayCollection中加载属性数据,在表单中预选多个值


Symfony 2 : preselect multiple values in a form by loading manualy attribute data from an ArrayCollection

我需要获得预选的一些值的实体属性,我得到在PRE_SET_DATA事件,而不是从数据库。

我有一个窗体工作,所有数据从我的实体AccessGroup加载,但我的问题是得到选择的ArrayCollection属性命名为accessGroups从实体用户这不是存储在数据库中。

说明一下,accessGroups属性是由User的角色加载的。

下面是FormType类
namespace Pkg'ExtranetBundle'Form;
use Doctrine'Common'Collections'ArrayCollection;
use Symfony'Component'Form'AbstractType;
use Symfony'Component'Form'FormBuilderInterface;
use Symfony'Component'OptionsResolver'OptionsResolver;
use Symfony'Component'Form'Extension'Core'Type'SubmitType;
use Symfony'Bridge'Doctrine'Form'Type'EntityType;
use Symfony'Component'Form'FormEvents;
use Symfony'Component'Form'FormEvent;
use Doctrine'ORM'EntityManager;

class RoleType extends AbstractType
{
    /**
     * @var EntityManager
     */
    protected $em;
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->em = $options['em'];
        $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));
    }
    /**
     * Listener before normalizing data form
     *
     * @param FormEvent $event
     */
    public function onPreSetData(FormEvent $event)
    {
        $user = $event->getData();
        $accessGroups = $this->em->getRepository('PkgExtranetBundle:AccessGroup')->getSelected($user->getRoles());
        $user->setAccessGroups(new ArrayCollection($accessGroups));
        $event->setData($user);
        $form = $event->getForm();
        $form->add('accessGroups', EntityType::class, array(
                'class'         => 'PkgExtranetBundle:AccessGroup',
                'choice_label'  => 'name',
                'choice_value'  => 'role',
                'multiple'      => true,
                'expanded'      => false
            ))
            ->add('save', SubmitType::class, array('label' => 'registration.submit', 'translation_domain' => 'FOSUserBundle'));
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Pkg'ExtranetBundle'Entity'User',
            'em' => null
        ));
    }
}

好了,我创建的类在choice_value参数上有自己的问题:

$form->add('accessGroups', EntityType::class, array(
                'class'         => 'PkgExtranetBundle:AccessGroup',
                'choice_label'  => 'name',
                'choice_value'  => 'role', // If choice_value is not the entity index, then preselection will not be applied as the index could not be retrieved.
                'multiple'      => true,
                'expanded'      => false
            ))