Wednesday, May 2, 2012

Symfony2 Forms - Cannot add/remove entities from a collection

I have a form for a "Person" entity that has a collection of "Nicknames".



I have implemented this following the guide in the cookbook (http://symfony.com/doc/current/cookbook/form/form_collections.html)



When I create a new "Person" I can add "Nicknames" as expected successfully.



Using a similar form I have an edit page. On the edit page I have set up the front end in the same way as the new page.



On the edit page, I can edit the existing nicknames and the other simple fields successfully. However, when I submit a new "Nickname" (or try to remove one), it does not work.



I have var_dump()'ed the request object before it is binded to the "Person" and I have var_dump()ed the "Person" object after binding. The request does have the "Nicknames" collection passed correctly. However, they are not being binded to the Person at all, despite the fact that everything is the same as the new page. Further, I can still edit the existing Nicknames so it is working on that front.



I cannot for the life of me figure out why Symfony isn't creating these new Nicknames or adding them to the Person as it should. I have looked around and searched but everything just confirms that it should be working - but it isn't.



Heres the entry for the Nicknames on the Person form type:



->add('nicknames', 'collection', array(
'type' => new NicknameType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
'required' => false
))


Nickname type only has one field - "nickname" and its a text input.



Any help? Thanks for reading.



EDIT:



Here is the update action (changed Person to Player):



public function updateAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();

$player = $em->getRepository('SCDBAppBundle:Player')->find($id);

if (!$player) {
throw $this->createNotFoundException('Unable to find Player.');
}

$editForm = $this->createForm(new EditPlayerType(), $player);
$deleteForm = $this->createGenericIDForm($id);

$editForm->bindRequest($request);

if ($editForm->isValid()) {
$em->persist($player);
$em->flush();

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

return array(
'player' => $player,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}


I realize that to actually persist removing nicknames I need to change the code to persist. I'm not even worried about persistence right now, because the main issue is that after I bind the request to the Player form, the $player object does not contain the updated Nicknames collection.





No comments:

Post a Comment