必须管理传递到选择字段的实体.也许将它们保留在实体管理器中



我是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();
    }

我有一个与我的公司类具有一对一关系的用户类,一切都是由 Doctrine 正确生成的。

我的目标是使用当前的公司列表制作一个用户创建表单,以允许用户选择一个并将其链接到他的帐户。

感谢您的帮助!

多亏了@Andariel,我的关系是错误的(需要一个 ManyToOne)

对于我的第二个问题,我能够使用 FOSUserBundle 的用户管理器注册用户,它就像一个魅力。

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

 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'));
    }

相关内容

最新更新