将当前实体设置为另一个

Set current entity to an other

我使用 symfony 2.8,我有两个实体:Cv 和 FormationCv, 一个 Cv 可以有多个 Formation Cv,所以我尝试使用关系 OneToMany 和集合 Type

CvType

class CvForm extends AbstractType
{

   public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder
             //..
            ->add('formations', CollectionType::class, array(

        'entry_type' => FormationCvForm::class,
        'allow_add'    => true,
        'by_reference' => false,

    ))             ;

}

FormationCvType

  class FormationCvForm extends AbstractType
{

   public function buildForm(FormBuilderInterface $builder, array $options)
   {
    $builder->add('titre')
            ->add('etablissement')
            ->add('description')

            ->add('dateDebut', DateType::class, array(
                                              'widget' => 'choice', 'translation_domain' => 'FOSUserBundle','data' => new \DateTime()))
            ->add('dateFin', DateType::class, array(
                                              'widget' => 'choice',
                                                    ))

            ;

}

控制器

public function createAction(Request $request)
  {
    $em = $this->getDoctrine()->getManager();
        $cv = new Cv();

$form = $this->createForm('Front\FrontBundle\Form\CvForm', $cv);
$form->handleRequest($request);

 if ($form->isSubmitted() && $form->isValid()) {
       $user=$this->get('security.context')->getToken()->getUser();
        $cv->setEtudiant($user);
        $cv->setTelephone($user->getTel());
        $cv->setDateNaissance($user->getBirthday());
        $cv->setActif(false);




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



        $em->persist($cv);
        $em->flush();
        $formations=$cv->getFormations();
        $formation= array();
        foreach ($formation as $formations) {
            $formation->setCv($cv->getId());
            $em->persist($formation);
             $em->flush();

        }




        return $this->redirectToRoute('cv_show', array('id' => $cv->getId()));

    }

return $this->render("FrontBundle:CV:createCv.html.twig", array(
        'form' => $form->createView(),

    ));

 }

如果我提交表单,在 FormationCv 的 table 中总是得到 Null 的问题, 有人帮我吗?

您的 foreach 不会 运行 一次迭代:

    $formations=$cv->getFormations();
    $formation= array();
    foreach ($formation as $formations) { // You're looping over $formation here, which is an empty array as per the line before this
        $formation->setCv($cv->getId());
        $em->persist($formation);
         $em->flush();

    }

删除 $formation= array(); 并在 foreach 条件中切换您的变量:foreach ($formations as $formation) {.

Alternatively/Preferably:通过设置您的实体以级联持久操作并告诉它反面(mappedBy / inversedBy),摆脱整个块并让学说完成工作。