如何重新使用Symfony2中遗留的一些字段 [英] How to re-use forms with some fields left out in Symfony2
问题描述
我使用嵌入式表单来创建一个注册表单,其中包含多个相关实体的字段。正如我在我的问题在这里解释:
Symfony2表单,其中数据对象不完全匹配需要填写的内容
这工作得很好。但是,假设我想重新使用我嵌入的其中一种表单,但是留下了一些字段。
那么我的选择是什么?
- 我是否创建了一个额外的formType来扩展原始的formType?
- 我在视图中决定留下一些字段吗?
虽然我觉得这不像是一个观点决定。对于每种不同的用例,扩展都会给我带来不好的重复使用习惯。
其他人怎么解决这个问题?
谢谢,
Dieter
我认为最好的解决方案是创建一个基础抽象类型,让你的类型扩展它。这里有一个简单的例子:
namespace Acme \Bundle\\ \\DemoBundle\Form\Type;
使用Symfony \Component\Form\AbstractType;
抽象FooBaseType扩展AbstractType
{
公共函数buildForm(FormBuilder $ builder,array $ options)
{
//添加所有通用的字段其他类型。
code
$ b现在你可以扩展它,包括缺少的字段
namespace Acme\Bundle\DemoBundle\Form\Type;
class ExampleType extends FooBaseType
{
public function buildForm(FormBuilder $ builder,array $ options)
{
parent :: buildForm($ builder, $选项);
//您缺少的字段
}
}
I am using embedded forms to be able to make a registration form, which holds fields of several related entities. As explained to me in my question over here:
Symfony2 form where the data objects doesn't match exactly what needs to be filled in
This works just fine. But say I want to re-use one of the forms that I embedded, but leave some of the fields out.
Then what are my options?
- Do I create an extra formType which extends the original one?
- Do I decide in the view to leave some fields out?
This doesn't feel like a view decision in my opinion though. And extending for each different use case feels like a bad re-use practice to me.
How are other people solving this?
Thanks,
Dieter
解决方案 I think the best solution is to create a base abstract Type and let your Types extend it. Here's a short example:
namespace Acme\Bundle\DemoBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
abstract FooBaseType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
// Add all fields common for your other types.
}
}
Now you can just extend it an include the missing fields
namespace Acme\Bundle\DemoBundle\Form\Type;
class ExampleType extends FooBaseType
{
public function buildForm(FormBuilder $builder, array $options)
{
parent::buildForm($builder, $options);
// Your missing fields
}
}
这篇关于如何重新使用Symfony2中遗留的一些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!