Php 你能';扩展';上课?
我支持我的表单,但不知道如何“扩展”它们 例如,我有一个Php 你能';扩展';上课?,php,symfony,Php,Symfony,我支持我的表单,但不知道如何“扩展”它们 例如,我有一个CustomerTypeform类和一个EmailTypeform类。我可以将电子邮件类型直接添加到我的客户类型 $builder->add('emails', 'collection', array( 'type' => new EmailType(), 'allow_add' => true, 'by_reference' => false )); 但是我更喜欢在控
CustomerType
form类和一个EmailType
form类。我可以将电子邮件类型
直接添加到我的客户类型
$builder->add('emails', 'collection', array(
'type' => new EmailType(),
'allow_add' => true,
'by_reference' => false
));
但是我更喜欢在控制器中执行此操作,这样我的CustomerType
表单类只包含客户信息。我觉得这更具模块化和可重用性,因为有时我希望我的用户能够只编辑客户
详细信息,而其他人既可以编辑客户
详细信息,也可以编辑与该客户关联的电子邮件
对象。(例如,第一种情况是查看客户的工单,第二种情况是创建新客户)
这可能吗?我在想一些关于
$form = $this->createForm(new CustomerType(), $customer);
$form->add('emails', 'collection', ...)
在我的控制器中。创建表单时,您可以向表单传递一个选项(例如“with\u email\u edition”),该选项将告诉表单是否应嵌入集合
在控制器中:
$form = $this->createForm( new CustomerType(), $customerEntity, array('with_email_edition' => true) );
格式为:
$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
}
}
为什么它可以重复使用?如果您有两个相同的表单,并且要重命名“电子邮件”字段,那么您可以在两个位置执行此操作。你的目标是什么?我在问题中澄清了一点。