Symfony 2.8 / 3.0 update: how to work with variable types of forms?

Let's say I create custom form types as services, as described in the Symfony documentation . But I want 2 "gender" user types with two different input parameters, which I did in Symfony 2.7:

# app/config/config.yml parameters: genders1: m: Male f: Female genders2: # This makes no sense at all, but it is for the example purpose! h: Horse t: Turtle 

And then I announced 2 such services:

 <!-- src/AppBundle/Resources/config/services.xml --> <service id="app.form.type.gender1" class="AppBundle\Form\Type\GenderType"> <argument>%genders1%</argument> <tag name="form.type" alias="gender1" /> </service> <service id="app.form.type.gender2" class="AppBundle\Form\Type\GenderType"> <argument>%genders2%</argument> <tag name="form.type" alias="gender2" /> </service> 

As you can see, I used the same GenderType for 2 custom form types (with the aliases gender1 and gender2 ), which I could use as follows:

 $builder ->add('field1', 'gender1') ->add('field2', 'gender2'); 

This allowed me to add some common logic in only one class ( GenderType ) with different input parameters (I have much more options in this example than 2).

But with Symfony 2.8, adding a field using a service alias is deprecated. The class name should be passed instead of the second argument, for example:

 $builder->add('field1', GenderType::class) 

So, how can I make the difference between my two services (each of which does not have the same input parameters)?

Creating Gender1Type and Gender2Type extending the Gender2Type abstract class would be very painful since I would have to create many classes with empty content.

Do you have any idea on how to implement my template in Symfony 2.8, keeping services with different input parameters, but not creating many classes?

+5
source share
1 answer

Well, after digging this section a bit more, someone already asked the question directly in PR regarding this change in Symfony 2.8.

And the answer is that the template that I did is no longer possible, so I see 2 solutions to my problem:

  • Create as many classes as I had services for my custom types, instead of using the same class all the time, and let these classes extend the abstract (in my example: create the Gender1Type and Gender2Type classes that extend the AbstractGenderType abstract class)
  • Keep only one class, but add parameters to it to pass my specific parameters.
+3
source

Source: https://habr.com/ru/post/1237560/


All Articles