你能扩展吗?表格类?

时间:2013-03-19 04:49:47

标签: php symfony

我的表格是creating form classes,但无法弄清楚如何“延伸”它们。

例如,我有一个CustomerType表单类和一个EmailType表单类。我可以将EmailType直接添加到我的CustomerType

$builder->add('emails', 'collection', array(
    'type'         => new EmailType(),
    'allow_add'    => true,
    'by_reference' => false
));

但我更喜欢在控制器中执行此操作,以便我的CustomerType表单类仅包含客户信息。我觉得这更具模块性和可重用性,因为有时我希望我的用户只能编辑Customer个详细信息,还有其他Customer个详细信息以及与该客户关联的Email个对象。 (例如,在查看客户工单的第一种情况下,以及在创建新客户时的第二种情况)。

这可能吗?

我正在考虑一些事情
$form = $this->createForm(new CustomerType(), $customer);
$form->add('emails', 'collection', ...)

在我的控制器中。

1 个答案:

答案 0 :(得分:0)

您可以在创建表单时将一个选项(例如“with_email_edition”)传递给您的表单,以确定表单是否应嵌入该集合。

在控制器中:

$form = $this->createForm( new CustomerType(), $customerEntity, array('with_email_edition' => true) );

格式:

只需在setDefaultOptions中添加选项:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
     $resolver->setDefaults(array(
                'with_email_edition' => null,
            ))
            ->setAllowedValues(array(
                'with_email_edition' => array(true, false),
            ));
}

然后在“buildForm”中检查此选项的值,并根据它添加一个字段:

public function buildForm(FormBuilderInterface $builder, array $options)
{
     if( array_key_exists("with_email_edition", $options) && $options['with_email_edition'] === true )
     {
          //Add a specific field with  $builder->add for example
     }
}
相关问题