How to re-use forms with some fields left out in Symfony2

 ̄綄美尐妖づ 提交于 2019-12-07 09:03:10

问题


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


回答1:


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



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!