传递给选择字段的实体必须被管理。也许将它们保存在实体管理器中?

Entities passed to the choice field must be managed. Maybe persist them in the entity manager?

我是 Symfony2 的新手,我没有收到此错误消息的任何答案

Entities passed to the choice field must be managed. Maybe persist them in the entity manager?

我的 Symfony 版本是 2.3

我在我的控制器 addAction() 中加入这样的代码

    $em = $this->getDoctrine()->getManager();

    $user = new User(); //User is my main entity
    $form = $this->createFormBuilder($user)
        ->add('company','entity', array(
            'class' => 'AGUserBundle:Company', //OneToMany child entity with User
            'property' => 'name',
            'multiple' => false
        ))
        ->getForm();

    $form->add('Ajouter', 'submit', array(
        'attr' => array('class' => 'btn btn-primary'),
    ));


    $request = $this->get('request');

    $form->handleRequest($request);

    if($form->isValid()){
        $em->persist($user);
        $em->flush();
    }

我有一个用户 class 与我的公司 class 有 OneToMany 关系,一切都由 Doctrine 正确生成。

我的目标是用当前的公司列表制作一个用户创建表单,允许用户选择一个并link它到他的帐户。

感谢您的帮助!

感谢@Andariel,我的关系是错误的(需要 ManyToOne)

对于我的第二个问题,我能够使用 FOSUserBundle 的 userManager 注册用户并且它非常有效。

这里是代码,如果它可以帮助某人:

 if($form->isValid()){
        //Getting the company from FORM Response
        $companyObject = $form->getData()->getCompany(); 

        //Setting company to user Obj
        $user->setCompany($companyObject); 

        //Persisting changes
        $userManager->updateUser($user,false);

        $this->get('session')->getFlashBag()->add(
            'notice',
            'User added !'
        );

        return $this->redirect($this->generateUrl('user_list'));
    }