【问题标题】:How to pass options to CustomType in `collection` field Symfony 2.1?如何在`collection`字段Symfony 2.1中将选项传递给CustomType?
【发布时间】:2013-03-06 22:04:31
【问题描述】:

我有SuperType 实体Super 的表单。

在这个表单中,我有一个 collection 字段 ChildType 实体 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
  ));
}

如何仅更改此 SuperType 表单的 my_custom_option 值?

当然,我尝试通过构造函数传递此选项的方法不起作用。

【问题讨论】:

  • 在这里留下一个link 解决同样的问题

标签: php forms symfony doctrine-orm


【解决方案1】:

您可以将array of options 传递给您的childType,如下所示:

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

}

【讨论】:

  • 考虑更新您的答案,因为现在已弃用
【解决方案2】:

在 Symfony 3 中,这称为entry_options

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多