2014-02-15 24 views
4

在symfony2中,我想生成多選選擇。 我想獲得這樣的事:Symfony Doctrine - 如何生成optgroup選擇表格

<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> 

我的位置實體爲:

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; 

因此MySQL的樣子:

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 

誰能幫我這個?

+0

你能pleasse解釋一下您到目前爲止試過嗎?你能包括迄今爲止的表單字段嗎? – nifr

回答

6

THX到a.aitboudad和我的朋友我已經找到了解決辦法。

我不得不輸入到我的Locaton實體:

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

然後我產生我的形式:

$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; 
       } 
      )) 
+0

真棒。比許多其他建議簡單得多 – DevDonkey

5

您可以在實體字段類型中添加選項group_by

例子:

$builder->add('children', 'entity', array(
    'class' => 'AcmeYourBundle:Location', 
    'group_by' => 'parent' 
    ... 
)); 
+0

沒想到這麼簡單 – edditor

相關問題