2013-03-18 104 views
17

我有SuperType表單爲實體Super如何在`collection`字段Symfony 2.1中將選項傳遞給CustomType?

在這種形式我有ChildType表單類型的collection領域實體Child

class SuperType:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder->add('childrens', 'collection', array(
      'type' => new ChildType(null, array('my_custom_option' => true)), 
} 

class ChildType:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    if ($options['my_custom_option']) { 
     $builder->add('my_custom_field', 'textarea')); 
    } 
} 

public function setDefaultOptions(OptionsResolverInterface $resolver) 
{ 
    $resolver->setDefaults(array(
     ... 
     'my_custom_option' => false 
)); 
} 

我如何更改my_custom_option的值只適用於此SuperType表單嗎?

當然,我試過通過構造函數傳遞這個選項是行不通的。

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder->add('childrens', 'collection', array(
      'entry_type' => new ChildType(), 
      'entry_options' => array(
       'my_custom_option' => true, 
      ), 
    // ... 

} 

回答

28

如下你可以傳遞一個array of options您childType。

$builder->add('childrens', CollectionType::class, array(
    'entry_type' => ChildType::class, 
    'entry_options' => array(
     'my_custom_option' => true 
    ), 
)); 
+2

考慮更新您的答案,因爲現在不推薦使用 – Trix 2016-12-24 15:25:55