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

ありがとう。

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 に答える