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

时间:2012-09-24 18:52:42

标签: 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',
                    );

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

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

感谢。

1 个答案:

答案 0 :(得分: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

相关问题