Search code examples
formssymfonyformbuilder

Symfony2 how to include a parent formType into another


i'm trieng to write a bundle for some fields. Now i got an class which i can extend. The class got some fields e.g. Title, Name etc.

Now i want to write a formType which can be extended by another formtype.

Like

class newsgroupType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('unusername','text',array(
                'required' => true))
        ->add('unactive','checkbox',array(
                'required' => false));
...

The FormType which i want to extend is

class mainType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('unurl','text',array(
              'required' => false,
              'disabled' => true))
        ->add('untitle','text',array(
              'required' => false))
...

Is there a way to extend the mainType to get all fields from it into my newsgroupType?

Thanks a lot =)


Solution

  • There is a cookbook article on the Symfony website that gives and example of how to extract common fields into a separate form definition which can then be included into other form definitions.

    Create a separate Form class that includes the common fields using the builder. You can then configure that form using the inherit_data option:

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'inherit_data' => true
        ));
    }
    

    The other forms can then add that form in the builder:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ...
    
        $builder->add('foo', new CommonType(), array(
            'data_class' => 'AppBundle\Entity\Foo'
        ));
    }