Rania MALK
Rania MALK

Reputation: 1

symfony 2.5 many to one relation foreign key null

i have two entities produit entity and avis with a many to one relation one product can have many avis but when i try to save a comment the field produit_id stay null. i have well configured the relation i think that i have a problem in the controller.

this is my controller add avis action:

public function addAction(Request $request){
    $em =$this->getDoctrine()->getManager();
    $produit=$em->getRepository('redeBundle:produit')->findAll();
    $avis = new avis();
    $avis->setCreatedAt(new \DateTime('now'));
    $form = $this->createForm(new avisType(), $avis);
    $form -> handleRequest($request);
    if($form->isSubmitted() && $form->isValid()){
       $avis->setProduit($produit);
        $em->persist($avis);
        $em->flush();
        return $this->redirect($this->generateUrl('produit_page'));
    }

    $formView=$form->createView();

    return $this->render('myBundle:avisAdd.html.twig',
     array('form'=>$formView));

}

this is my entity avis

class avis {

/**
 * @var produit
 *
 * @Assert\valid()
 *
 * @ORM\ManyToOne(targetEntity="redemaroc\redeBundle\Entity\produit", 
cascade={"persist"})
 * @ORM\JoinColumn(nullable=false)
 *
 *
 */
private $produit;

 ...
 }

can someone help me resolve that ?!

Upvotes: 0

Views: 38

Answers (1)

Mercury
Mercury

Reputation: 1

It is solvable by using on of those solutions

  1. in the setProduit method of your Avis class, you add the following instruction: produit->addAvis($this);.
  2. Make sure that anytime you call $avis->setProduit($produit);, you must add $produit->addAvis($avis); before flush your data.

I am supposing that addAvis is the method used to add a given avis to your produit.

Upvotes: 0

Related Questions