symfony2实体表单类型中的选项组

jam*_*ond 1 php symfony symfony-2.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',
                    );
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢.

Jea*_*ean 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',
            ));
}  
Run Code Online (Sandbox Code Playgroud)

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

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;
} 
Run Code Online (Sandbox Code Playgroud)

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

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

class MyAccountType extends AbstractType {

    private $em;

    public function __construct(\Doctrine\ORM\EntityManager $em){
        $this->em = $em; 
    }    
} 
Run Code Online (Sandbox Code Playgroud)

EntityManager在你启动MyAccountType对象时通过.