Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Embedded forms, How to persist objects

Tags:

symfony

I am trying to implement Embedded Forms (Symfony2, 2.7), with Task and Tag entities, One2Many.

To save reference to the Task object into a Tag record, I am able to define Task's createAction() only by:

/**
 * Creates a new Task entity.
 *
 * @Route("/", name="MyName_Task_create")
 * @Method("POST")
 * @Template("MyNameBundleBlogBundle:Task:new.html.twig")
 */
public function createAction(Request $request)
{
    $task = new Task();
    $form = $this->createCreateForm($task);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $tags = $task->getTags();
        foreach($tags as $tg){$tg->setTask($task); $em->persist($tg);}   // <-- do I really need to loop?
        $em->persist($task);
        $em->flush();

        return $this->redirect($this->generateUrl('MyName_Task_show', array('id' => $task->getId())));
    }

    return array(
        'entity' => $task,
        'form'   => $form->createView(),
    );
}

EDIT: I know it should work without the loop straightforwardly, but it does not. Question is: What should I look for which I might have written wrong? See related question

Note, I have:

class Task{
....
 /**
 *
 * @ORM\OneToMany(targetEntity="Tag", mappedBy="Task", cascade={"persist"} )
 */
private $Tags;
....
 /**
 * Add tag
 *
 * @param \MyName\Bundle\BlogBundle\Entity\Tag $tag
 *
 * @return Task
 */
public function addTag(\MyName\Bundle\BlogBundle\Entity\Tag $tag)
{
    $this->tags[] = $tag;
    $tag->setTask($this);
    return $this;
}
}
like image 473
mario Avatar asked Jun 03 '26 21:06

mario


1 Answers

No, you don't need to loop through all tags and explicitly set task, Symfony will do that for you if you configure it correctly.

The only thing you need to add is set by_reference to false inside your form builder. In this case, symfony will explicitly will call setTask on every tag.

For more info 'by_reference'

like image 148
Turdaliev Nursultan Avatar answered Jun 08 '26 00:06

Turdaliev Nursultan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!