Reynier
Reynier

Reputation: 2478

ManyToMany bidirectional relationship doesn't save data

I have a many to many relationship between product and product_details tables which results in a third table called product_has_product_details. I made this code:

ProductBundle\Entity\ProductDetail.php

/**
 * @ORM\ManyToMany(targetEntity="CategoryBundle\Entity\Category", mappedBy="pd_category")
 */
protected $category;

public function __construct() {
    $this->category = new \Doctrine\Common\Collections\ArrayCollection();
}

public function setCategory($category) {
    $this->category[] = $category;
}

CategoryBundle\Entity\Category.php

/**
 * @ORM\ManyToMany(targetEntity="ProductBundle\Entity\ProductDetail", inversedBy="category")
 * @ORM\JoinTable(name="product_detail_has_category")
 */
protected $pd_category;

public function __construct() {
    $this->pd_category = new \Doctrine\Common\Collections\ArrayCollection();
}

And in my controller ProductDetailController.php have this code:

/**
 * Handle category creation
 *
 * @Route("/pdetail/create", name="pdetail_create")
 * @Method("POST")
 * @Template("ProductBundle:ProductDetail:new.html.twig")
 */
public function createAction(Request $request) {
    $entity = new ProductDetail();
    $form = $this->createForm(new ProductDetailType(), $entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $entity->setValuesText(serialize($form->get('values_text')->getData()));
        $em->persist($entity);
        $em->flush();

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

    return $this->render('ProductBundle:ProductDetail:new.html.twig', array(
                'entity' => $entity,
                'form' => $form->createView(),
    ));
}

When I send the form, values for ProductDetail are saved but values for relationship not and I can't find where is the issue. Also I get this error:

The controller must return a response (Array(product_details => Array(0 => Object(ProductBundle\Entity\ProductDetail), 1 => Object(ProductBundle\Entity\ProductDetail), 2 => Object(ProductBundle\Entity\ProductDetail))) given).

Can any help me?

Upvotes: 1

Views: 333

Answers (1)

Flip
Flip

Reputation: 4908

It would be nice if you would show the ProductDetail->setValuesText method. But in any case you have to make a new Category object (or take an already existing one). And then do

$category = new Category();
$em->persist($category);
$productDetail->setCategory();
$em->persist($productDetail);
$em->flush();

Upvotes: 1

Related Questions