将当前实体设置为其他实体

时间:2017-05-04 11:20:39

标签: symfony symfony-2.8

我使用symfony 2.8,我有两个实体:Cv和FormationCv, 一个Cv可以有很多编队Cv,所以我尝试用关系OneToMany和集合类型

来做

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表中总是得到Null的问题, 有人帮帮我吗?

1 个答案:

答案 0 :(得分:2)

你的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) {

替代/优选:摆脱整个块,让学说通过设置实体来级联持久化操作并告诉它有关反面(mappedBy / inversedBy)来完成工作。