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 ?
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;
}
))
You can just add option group_by in your entity field type.
Example:
$builder->add('children', 'entity', array(
'class' => 'AcmeYourBundle:Location',
'group_by' => 'parent'
...
));
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');
},
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With