1

有没有什么方法可以在 symfony2 (v.2.1) 的选项组中分组显示实体字段,例如我的表单类中有这样的内容:

$builder->add('account',
                    'entity',
                    array(
                        'class' => 'MyBundle\Entity\Account',
                        'query_builder' => function(EntityRepository $repo){
                            return $repo->findAllAccounts();
                        },
                        'required'  => true,
                        'empty_value' => 'Choose_an_account',
                    );

但是(当然)它们显示为存储库类从数据库中读取它,我想将它们分组显示在组合框中。这篇文章提到了开箱即用的 2.2 版本中添加的功能,但我们 2.1 用户有哪些选择?

分组将基于一个名为 的字段Type,假设我有一个getType()在我的 Account 实体中调用的 getter,它返回一个字符串。

谢谢。

4

1 回答 1

5

在处理类别时我做了类似的事情。

首先,当您构建表单时,将选项列表作为函数的结果传递,getAccountList()如下所示:

 public function buildForm(FormBuilderInterface $builder, array $options){
        $builder        
            ->add('account', 'entity', array(
                'class' => 'MyBundle\Entity\Account',
                'choices' => $this->getAccountList(),
                'required'  => true,
                'empty_value' => 'Choose_an_account',
            ));
}  

该函数应该执行如下操作(内容取决于您构建结果的方式)。

private function getAccountList(){
    $repo = $this->em->getRepository('MyBundle\Entity\Account');

    $list = array();

    //Now you have to construct the <optgroup> labels. Suppose to have 3 groups
    $list['group1'] = array();
    $list['group2'] = array();
    $list['group3'] = array(); 

    $accountsFrom1 = $repo->findFromGroup('group1'); // retrieve your accounts in group1.
    foreach($accountsFrom1 as $account){
        $list[$name][$account->getName()] = $account;
    }
    //....etc

    return $list;
} 

当然,你可以做更多的动态!我的只是一个简单的例子!

您还必须将 传递EntityManager给您的自定义表单类。所以,定义构造函数:

class MyAccountType extends AbstractType {

    private $em;

    public function __construct(\Doctrine\ORM\EntityManager $em){
        $this->em = $em; 
    }    
} 

EntityManager并在您启动MyAccountType对象时传递。

于 2012-12-04T18:27:46.140 回答