Symfony2でFormTypeを使用する時に他のメソッドを使用できないか?

491 views
Skip to first unread message

takashi tabata

unread,
Aug 28, 2013, 8:59:24 PM8/28/13
to symfony-...@googlegroups.com
おはようございます。
田端と申します。

Symfony2でForm/Typeを使用フォームの作成をしているのですが
1つのbuildFormを2つに分けたりしたいのですがそういう指定はできるのでしょうか?

わかりにくいのですが、下記のやり方でTypeにbuildFormとは別にbuildFormAddressを別で作成しています。
このbuildFormAddressを読みにいく様にしたいです。



# Contoller側

// 普通の書き方
$this->form = $this->createForm(new ExampleType());

// 読みに行きたいけどエラーになる書き方
$type = new ExampleType();
$this->form = $this->createForm($type->buildFormAddress());




# Type側

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', 'text', ['label' => '企業名'])
        ->add('ruby', 'text', ['label' => 'ふりがな']);
}


public function buildFormAddress(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('zip', 'text', ['label' => '郵便番号'])
        ->add('address', 'text', ['label' => '住所']);
}




何かアドバイスいただけると助かります。
宜しくお願い致します。

Yuichi Okada

unread,
Aug 29, 2013, 12:41:41 PM8/29/13
to symfony-...@googlegroups.com
はじめまして。
岡田と申します。

これだけですと質問の内容(作りたい物)がいまいち理解できないのですが、
状況に応じてformを出し分けしたいということでしょうか?

例に挙げられた、エラーになる場合の書き方はできません。

createFormに渡す引数は FormrInterface を実装したものでなければなりません。
通常AbstractTypeを継承したクラス(この例だとExampleTypeクラス)を作って
引数に渡すことがほとんどだと思います。


同じTypeクラス内でbuildFormロジックを切り替えたいのであれば、$option 引数を渡す方法があります。

// コントローラー
$options = array('disableAddress' => true);
$this->createForm(new ExampleType() new ExampleEntity(), $options);

class ExampleType 
{public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', 'text', ['label' => '企業名'])
        ->add('ruby', 'text', ['label' => 'ふりがな'])
    ;
    if ($options['enableAddress']) {
        $builder
            ->add('zip', 'text', ['label' => '郵便番号'])
            ->add('address', 'text', ['label' => '住所'])
        ;
    }
}

この様に書けば$options引数によって挙動を変えることができるかと思います。

このサンプルコードですと企業情報と住所情報の両方をフォームとして表示することなります。
参考になれば幸いです。

もし、見当違いの回答をしてしまっていたようであれば教えていただけますと助かります。

岡田

2013年8月29日木曜日 9時59分24秒 UTC+9 takashi tabata:

2013年8月29日木曜日 9時59分24秒 UTC+9 takashi tabata:

takashi tabata

unread,
Aug 30, 2013, 4:02:26 AM8/30/13
to symfony-...@googlegroups.com
岡田様

教えていただきありがとうございます。
自己解決ですが、Validatorのグループ化を行う事で解決する事が出来ました。

今度は、岡田様が教えてくれた方法で挑戦してみたいと思います。

ありがとうございました。

2013年8月30日金曜日 1時41分41秒 UTC+9 Yuichi Okada:
Reply all
Reply to author
Forward
0 new messages