Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Doctrine - how to generate optgroup select form

In symfony2 I would like to generate multiselect selections. I would like to get something like this :

 <select>
  <optgroup label="district 1">
    <option>city 1</option>
    <option>city 2</option>
  </optgroup>
  <optgroup label="district 2">
    <option>city X</option>
    <option>city Y</option>
  </optgroup>
</select>

my Location Entity is:

class Location
{
    /**
     * @var integer
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
    * @ORM\ManyToOne(targetEntity="Location", inversedBy="children")
    * @ORM\JoinColumn(name="pid", nullable=true)
    */
    protected $parent;
    /**
    * @ORM\OneToMany(targetEntity="Location", mappedBy="parent")
    */
    protected $children;    
    /**
     * @var string
     * @ORM\Column(name="name", type="string", length=255)
     */
    protected $name;

so mysql looks like :

id, pid, name
1, null, district 1
2, null, district 2
3, 1, city 1
4, 1, city 2
5, 2, city X
6, 2, city Y

Can anyone help my with this ?

like image 241
Jan Furi Avatar asked Feb 15 '14 13:02

Jan Furi


3 Answers

thx to a.aitboudad and a friend of mine I have found the solution.

I had to type into my Locaton entity :

    public function getParentName() { 
    return $this->getParent() ? $this->getParent()->getName() : null;         
}

then I generated my form by :

$builder->add('locations', 'entity', array(
                'class' => 'MyBundle:Location',
                'group_by' => 'parentName',
                'property' => 'name',
                'query_builder' => function (\Doctrine\ORM\EntityRepository $repo) {
                     $qb = $repo->createQueryBuilder('l');
                     $qb->andWhere('l.parent IS NOT NULL');

                     return $qb;
                }
            ))  
like image 153
Jan Furi Avatar answered Oct 11 '22 14:10

Jan Furi


You can just add option group_by in your entity field type.

Example:

$builder->add('children', 'entity', array(
    'class'    => 'AcmeYourBundle:Location',
    'group_by' => 'parent'
    ...
));
like image 20
a.aitboudad Avatar answered Oct 11 '22 13:10

a.aitboudad


Symfony 4 solution, pretty simple.

You can simply use the 'parent.field' notation.

 ->add('campaign', EntityType::class,[
                'class' => Campaigns::class,
                'required' => false,
                'choice_label' => 'name',
                'group_by' => 'client.name',
                'query_builder' => function (CampaignsRepository $er) {
                    return $er->createQueryBuilder('c')
                        ->orderBy('c.name', 'ASC');
                },

            ])
like image 1
Chris Avatar answered Oct 11 '22 13:10

Chris