你能不能'表单类


Can you 'extend' 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', ...)

你可以在表单创建时传递一个选项(比如"with_email_edition")来告诉表单是否应该嵌入集合

In the Controller:

$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
     }
}