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
}
}
see this github pull request: https://github.com/symfony/symfony-docs/pull/765
it seems to be exactly what you are looking for.
来源:https://stackoverflow.com/questions/7724564/how-to-re-use-forms-with-some-fields-left-out-in-symfony2