K. Weber
K. Weber

Reputation: 2773

Persist entity in controller POST action for EasyAdminBundle

I'm trying to add some custom action in symfony EasyAdminBundle, I just added a form view with no problem, but the problem is with this form POST action, it is another method of same controller, which works well, but when I do persist() and flush() for entity manager it just does nothing. This is my code, everything works as expected except that changes are not applyed in database.

/**
 * @Route("/product-segment/save/{id}", name="admin_product_segment_save")
 */
public function saveSegmentsAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $product = $em->getRepository('AppBundle:product')->find($id);

    foreach ($product->getSegments() as $segment)
    {
        error_log("Product has segment " . $segment->getId());
    }

    $product->removeAllSegments();

    foreach ($product->getSegments() as $segment)
    {
        error_log("Now prod has  " . $segment->getId());
    }

    $em->persist($product);
    $em->flush();

    foreach ($this->getRequest()->request->all() as $post_var => $segment_id)
    {
        if ($post_var == 'segment_id')
        {
            $segment = $em->getRepository('AppBundle:Segment')->find($segment_id);
            $product->addSegment($segment);
        }
    }
    $em->persist($product);
    $em->flush();

    // redirect to the 'list' view of the given entity
    return $this->redirectToRoute('admin', array(
        'view'   => 'list',
        'entity' => 'Product',
    ));
}

EDIT: This is my entity relation

/**
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Segment", mappedBy="products", cascade={"all"})
 * @ORM\JoinTable(
 *      joinColumns={@ORM\JoinColumn(onDelete="CASCADE")},
 *      inverseJoinColumns={@ORM\JoinColumn(onDelete="CASCADE")}
 * )
 */
protected $segments;

Upvotes: 0

Views: 1812

Answers (1)

Simon Berton
Simon Berton

Reputation: 528

First you should only call the flush once in your code, and if you have your object the way you do:

$em = $this->getDoctrine()->getManager(); $product = $em->getRepository('AppBundle:product')->find($id);

You don't have to persist it again. The entity manager already has that object. Regarding the action not doing anything. Check if ManyToMany relation is defined Ok in both sides. And your method removeAllSegments does what you want it to do.

http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/association-mapping.html

Upvotes: 0

Related Questions