Symfony FormType getParent vs Inheritance

When creating a custom field in Symfony, there is a method that we define getParent

We define our class by extending the AbstractType class, then return the parent type using the getParent method. instead of extending from the parent class.

I want to know the philosophy of this approach.

Is it possible to define my custom type, for example:

class ImageType extends FileType { public function getName() { return 'image'; } } 

instead of this:

 class ImageType extends AbstractType { public function getParent() { return 'file'; } public function getName() { return 'image'; } } 

If so, then what is the difference between these two approaches?

Thanks!

+7
symfony symfony-forms
source share
2 answers

There are two main differences:

  • The first is about FormTypeExtension s. These extensions modify certain types of forms (for example, they can change / add some default parameters or even add a field).
    Using the first approach (for example, Inheritance ), all extensions for the ImageType type will be applied to ImageType , but using the second approach (for example, getParent ), they will not, thus, you will have more control over your structure.

  • The second difference is changing the behavior of the parent form inside the child form using buildForm and buildView .
    Using the first approach (e.g. Inheritance ) will override the methods of the base class if you expose them to child, but the second approach (e.g. getParent ) will add the child logic to the parent logic.

Consider the following example:

  // FileType public function buildForm(FormBuilderInterface $builder, array $options){ $builder->add('name', 'text'); } // ImageType public function buildForm(FormBuilderInterface $builder, array $options){ $builder->add('email', 'email'); } 
  • Inheritance:

    form fields: [ email ]

  • Getparent

    form fields: [ name ] [ email ]

+7
source share

No, you need to expand the use of AbstractType. This is used to display and build a form and is not a simple object that you distribute. The basic type of FileType in your case refers to a file with certain methods, and you will be allowed to easily override them, but expand through AbstractType and can add new fields. If you extended FileType, I don't think Symfony2 will load any new features properly.

I think the first method is more compact and would like to use it, but I think this can cause problems if you configure buildView or setDefaultOptions or add another method that was not part of the base type.

0
source share

All Articles