doctrine2 - Entity field type symfony 2.0 - show data from database in edit action -
here situation:
i have 3 tables (one-to-many): product, productlabel, labeltag (label reserved -_-)
as may have guessed, product can have many labels.
now have form product shows labels available. new , create actions have been able show , save labels selected. problem comes when try display labels + show selected labels in edit action database.
some code:
entity product:
/** * @var doctrine\common\collections\arraycollection $productlabels * * @orm\onetomany(targetentity="labeyrie\bundle\mainsitebundle\entity\productlabel", mappedby="product") */ protected $productlabels;
entity labeltag:
/** * @var doctrine\common\collections\arraycollection $productlabels * * @orm\onetomany(targetentity="labeyrie\bundle\mainsitebundle\entity\productlabel", mappedby="labeltag") */ protected $productlabels;
entity productlabel:
/** * @var labeyrie\bundle\mainsitebundle\entity\product $product * * @orm\id * @orm\manytoone(targetentity="labeyrie\bundle\mainsitebundle\entity\product", inversedby="productlabels") */ protected $product; /** * @var labeyrie\bundle\mainsitebundle\entity\labeltag $labeltag * * @orm\id * @orm\manytoone(targetentity="labeyrie\bundle\mainsitebundle\entity\labeltag", inversedby="productlabels") */ protected $labeltag;
product form:
->add('productlabels', 'entity', array( 'class' => 'labeyriemainsitebundle:labeltag', 'property' => 'title', 'multiple' => true, 'expanded' => true, ))
here how saved in create action:
if ($form->isvalid()) { /* save product */ $em->persist($product); $em->flush(); /* save product labels */ $labels = $product->getproductlabels(); if (!empty($labels)) { foreach ($labels $label) { $productlabel = new productlabel(); $productlabel->setlabeltag($label); $productlabel->setproduct($product); $em->persist($productlabel); } } $em->flush(); }
no problem that.
problem in edit action:
$entity = $em->getrepository('myprojectbundle:product')->find($id)); $form = $this->createform(new producttype(), $entity);
if render form, see labels, information ones have been selected not transmitted (since in middle table manage) , not shown.
i need solution using one-to-many architecture. form configuration wrong? please help. :)
i found answer:
simply need following:
$collection = new arraycollection(); $labels = $entity->getproductlabels(); if (!empty($labels)) { foreach ($labels $label) { $collection->add($label->getlabeltag()); } } $form->get('productlabels')->setdata($collection);
retrieve individual object (labeltag), put in array collection, pass collection form field's data , done.
the form displayed , selected options shown.
Comments
Post a Comment