【问题标题】:Symfony Doctrine - how to generate optgroup select formSymfony Doctrine - 如何生成 optgroup 选择表单
【发布时间】:2014-02-15 13:28:01
【问题描述】:

在 symfony2 中,我想生成多选选择。 我想得到这样的东西:

 <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

谁能帮我解决这个问题?

【问题讨论】:

  • 您能解释一下您到目前为止所做的尝试吗?你能包括你到目前为止的表单域吗?

标签: forms symfony doctrine


【解决方案1】:

感谢 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;
                }
            ))  

【讨论】:

    【解决方案2】:

    您可以在实体字段类型中添加选项group_by

    例子:

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

    【讨论】:

    • 没想到这么简单
    【解决方案3】:

    Symfony 4 解决方案,非常简单。

    您可以简单地使用“parent.field”表示法。

     ->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');
                    },
    
                ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      相关资源
      最近更新 更多