Symfony 2 How do I embed collection form using some criterias

collections, embed, forms, symfony

Solution

It's seems that I have to filter the object before using CreateQuery and then create the form using this filtered object. Like this:

$parent = $this->getDoctrine()->getEntityManager()->createQuery("
            SELECT p, c 
            FROM AcmeBundle:Parent p
            JOIN p.children c
            WHERE c.attribute1 = :attr1
              AND c.attribute2 = :attr2
           ")
           ->setParameter('attr1', <some_value>)
           ->setParameter('attr2', <some_value>)
           ->getOneOrNullResult();
$forms = $this->createForm( new ParentChildType(), $parent)->createView();
....
return array('forms' => $form->createView());           

Problem

I have a problem using the embed collection forms because I want to filter the data displayed on the collection given. i.e. ``` <?php Class Parent { ... some attributes ... /** * @ORM\OneToMany(targetEntity="Child", mappedBy="parent", cascade={"all"}) */ private $children; ... some setters & getters ... } Class Child { private $attribute1; private $attribute2; /** * @ORM\ManyToOne(targetEntity="Parent", inversedBy="children") * @ORM\JoinColumn(name="parent_id", referencedColumnName="id") */ private $parent; ... some setters & getters ... } ``` Then I build the form using: ``` class ParentChildType extends AbstractType { public function buildForm(FormBuilder $builder, array $options) { $builder ->add('children', 'collection', array( 'type' => ChildrenType(), 'allow_add' => true, )); } } ... On controller: $parent = $this->getDoctrine()->getEntityManager()->getRepository('AcmeBundle:Parent')->find( $id ); $forms = $this->createForm( new ParentChildType(), $parent)->createView(); and then.. return array('forms' => $forms->crateView()); ``` My problem is when I want to filter the collection by `$attribute1` and/or `$attribute2` of `Child` model class. There's a way to filter by a criteria for this collection forms?

Original source

Related problems