Reputation: 369
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?
Upvotes: 3
Views: 1135
Reputation: 44831
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);
// ...
}
Upvotes: 3
Reputation: 11351
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
Upvotes: 1