Symfony 2 How to insert a collection form using some criteria

I have a problem using inline collection forms because I want to filter the data displayed in the given collection. 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 create 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 a collection using $attribute1and / or a $attribute2model class Child.

Is there a way to filter by criteria for these collection forms?

+3
source share
2 answers

It seems that I should 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());           
+4
source

I am pointing you in the right direction (hopefully):

http://www.craftitonline.com/2011/08/symfony2-ajax-form-republish/

. , , , , .

,

0

All Articles