2016-10-27 9 views
-1

が、私はカスタムフィールドSymfony2.xはsymfony 2.xで

でProductTypeフォームクラス

public function __construct(array $aCustomFieldsList) 
{ 
    $this->aCustomFields = $aCustomFieldsList; 
} 

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('name', TextType::class, [ "label" => "Name" ]) 
     ->add('price', MoneyType::class, [ "label" => "Price" ]); 


    foreach($this->aCustomFields as $n=>$sCustomField) 
    { 
     $builder->add($sCustomField, TextType::class, [ "label" => {$sCustomField}"]); 
    } 

    $builder->add('save', SubmitType::class, [ "label" => "Save" ]); 
} 

とコントローラのあるフォームを表示するには、この方法を使用するフォーム

$form = $this->createForm(new ProductType($aCustomFields), $product); 

symfony 3.xでは、メソッドcreateForm()の最初の引数はインスタンス化されたオブジェクトはもうありませんが、名前空間を持つクラス名を表す文字列は次のようになります。

$form = $this->createForm(ProductType::class, $product); 

Symfony 3.xで行ったのと同じようにする方法はありますか?

+0

は、オプションパラメータを経由して、カスタムフィールドを渡します。そして、Forms 2からForms 3への移行は苦労する可能性があります。あなたはおそらくより多くの問題にぶつかるでしょう。 – Cerad

答えて

1

Ceradが示唆しているように、オプションフィールドを使用してこれらのオプションを渡すことができます。これは2.xでも推奨されました。次に、オプション要件を定義します。私が持っているようにフィールドを必要とするならば、フォームをビルドするときに提供されていなければ、エラーが発生します。

// Form Type 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 

    $builder 
     ->add('name', TextType::class, [ "label" => "Name" ]) 
     ->add('price', MoneyType::class, [ "label" => "Price" ]); 


    foreach($options['custom_field_list'] as $n=>$sCustomField) 
    { 
     $builder->add($sCustomField, TextType::class, [ "label" => {$sCustomField}]); 
    } 

    $builder->add('save', SubmitType::class, [ "label" => "Save" ]); 
} 

public function configureOptions(OptionsResolver $resolver) 
{ 
    $resolver->setDefaults([ 
     'custom_field_list' => [], 
    ]); 
    $resolver->setRequired([ 
     'custom_field_list' => true 
    ]); 
    $resolver->setAllowedTypes([ 
     'custom_field_list'=>'array' 
    ]); 
} 

次にコントローラでそれを呼び出す:

//controller 

$form = $this->createForm(ProductType::class, $product, [ 
    'custom_field_list' => $aCustomFields 
]); 
関連する問題