symfony - Bind and save a form with a collection field using an array / Doctrine2 -
i have 2 entities
room.php
/** * @orm\table(name="room") * @orm\entity(repositoryclass="ahsio\stackbundle\repository\roomrepository") */ class room { /** * @orm\id * @orm\column(type="integer") * @orm\generatedvalue(strategy="auto") */ protected $id; // ... /** * @orm\onetomany(targetentity="ahsio\stackbundle\entity\workstation", mappedby="room", cascade={"persist", "remove"}, orphanremoval=true) */ protected $workstations;
and workstation.php
/** * @orm\table(name="workstation") * @orm\entity(repositoryclass="ahsio\stackbundle\repository\workstation") */ class workstation { /** * @orm\id * @orm\column(type="integer") * @orm\generatedvalue(strategy="auto") */ private $id; /** * @orm\manytoone(targetentity="ahsio\stackbundle\entity\room") * @orm\joincolumn(name="room_id", referencedcolumnname="id", nullable=false) */ private $room; // ...
i added room type collection field adding/updating/removing workstations
roomtype.php
class roomtype extends abstracttype { public function buildform(formbuilder $builder, array $options) { $builder ->add('id', 'hidden', array( 'read_only' => true, )) // .... ->add('workstations', 'collection', array( 'type' => new workstationtype(), 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false, )) ; } // ... }
the workstation type simple 1 2 fields (id
& number
).
the problem when i'm trying bind roomtype existing room (which contains 2 workstations of id (1 , 2)) following array (which contains 1 of 2 workstations):
array(4) { ["id"]=> string(1) "3" ["workstations"]=> array(1) { [0]=> array(2) { ["id"]=> int(1) ["number"]=> int(200) } }
the update done, workstation id=2 removed. when i'm trying remove workstations given room using:
array(4) { ["id"]=> string(1) "3" ["workstations"]=> array(0) { }
the workstations still there, bind did performed, here got when did $form->getdata() after binding $form using last given array:
object(ahsio\stackbundle\entity\room)#229 (4) { ["id":protected]=> string(1) "3" ["name":protected]=> string(20) "first room (updated)" ["description":protected]=> string(39) "this first room old 1 (updated)" ["workstations":protected]=> array(0) { } }
so, no workstations updated room. can tell me why workstations aren't deleted when persist last binded room?
here part of controller code i'm using test update ...
// room $id given ... $roomarray = array( 'id' => $id, 'name' => 'first room (updated)', 'description' => 'this first room old 1 (updated)', 'workstations' => array(), ); $form = $this->createform(new roomtype(), $room); $form->bind($roomarray); if ($form->isvalid()) { $em = $this->getdoctrine()->getentitymanager(); $em->persist($room); $em->flush(); }
i think setter receives workstations
array never called because array empty.
try see if called adding trace.
also, should add cascade="merge" option in workstations mapping.
Comments
Post a Comment