简体   繁体   中英

Symfony2 OneToMany relationships and forms

I have been using Symfony2 for a new project and have run into a rather silly problem.

I have a OneToMany relationship between my two doctrine entities Item and Comment. I now have a form for a user to create a new comment for a given Item. When creating a new comment this comment of course has a property Item, and this should be set to the item currently being commented on.

When clicking the comment link on an Item an id is send along as a parameter to the form page, my plan was to have this id populate a hidden field that would then be transformed to an Item on postback using a Data Transformer.

But how do I actually make this work? How do I get this id into a hidden field in the form, so it can be properly handled by the Data Transformer? Or are there a better/more correct way of handling such relationships when using forms in Symfony2?

You don't need a hidden field for this. Your action has to know which item a user is commenting, so you can set the item on the comment:

/**
 * @Route("/item/{id}/comment")
 */
public function commentAction(Item $item)
{
    $comment = new Comment;
    $comment->setItem($item);

    $form = $this->createForm('item_comment', $comment);

    // ...
}

No need for data transformer. Just create a form field for your 'Item' property and set it as hidden. Something like

    $item = $this->getDoctrine()
    ->getRepository('AcmeDemoBundle:Item')
    ->find($id);

    $comment = new Comment();
    $comment->setItem($item);

    $form = $this->createFormBuilder($comment)
            ... //add some fields
            ->add('item', array('hidden'=>true));
            ->getForm();

When you receive the form and bind it, the 'item' property of the Comment object will be correctly set

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM