Search code examples
formssymfonydoctrinemany-to-manylimit

Symfony2 Form: Show select based on underlying Data (many-to-many)


I have three Entities:

class Product {
    /**
     * @ORM\ManyToMany(targetEntity="Colour")
     * @ORM\JoinTable(name="Product_Colour",
     *      joinColumns={@ORM\JoinColumn(name="product_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="colour_id", referencedColumnName="id")}
     * )
     */
    protected $colours;
}

class Colour {
    /**
     * @ORM\ManyToMany(targetEntity="Product", mappedBy="colours")
     **/
    protected $products;
}

class BasketProduct {
    /**
     * @ORM\ManyToOne(targetEntity="Colour")
     * @ORM\JoinColumn(name="colour_id", referencedColumnName="id")
     **/
     private $colour;

    /**
     * @ORM\ManyToOne(targetEntity="Product")
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     */
    protected $product;
}

There are many Colours in Colour. Every Product can be in several Colours.

Via a Link I can add a Product to my BasketProduct and in the next step I can select the Colour of the BasketProduct. What I need is a way to limit the Colour select field only to the Colours avaiable for the Product. This is my try, but it is showing me all colours:

$builder->add('colour', 'entity', array('class' => 'Colour',
                                            'query_builder' => function(EntityRepository $er) {
                                                                    return $er->createQueryBuilder('u')
                                                                            ->select('u','i')
                                                                            ->leftJoin('u.products','i');
                                                                },
                                        ));

A solution will be very appreciated! Thank you! :)


Solution

  •     $builder->add('colour', 'entity', array('class' => 'Colour',
            'query_builder' => function(EntityRepository $er) {
                return $er->createQueryBuilder('c')
                    ->select('c')
                    ->join('c.products','p');
            },
        ));
    

    Edit: fix spell, join method(instead of 'Join')