简体   繁体   中英

Symfony2 change form labels based on url

I have several versions of a form that exist. The form has all the same questions but the labels for the form are different based on who is filling it out (1st vs 3rd person).

Does anyone have any ideas on how to approach accomplishing this. I know I could create a different set of templates however the form is rather large and it would be nice to change it on the fly.

I ask because I find that Symfony's tool bag is large and I am afraid I am overlooking something. As of right now the only way I see possible is using an Event Listener .

Any help is appreciated!

It seems your talking strictly about the presentation layer. I would investigate using translations for this. Having multiple form classes or a bunch of logic in your controller will be frustrating. You mentioned first and third person. How do you determine if a user is in one of those groups? Perhaps you create a wrapper service for the translation component which checks your requirements and delegates accordingly. It seems like all your doing is speaking another language.

Your main issue is determining whom is first person and whom is third person. Does that change throughout the session? If not do that in your authentication process ( a security voter could work for the determination ) or/and store it in the session if it does change. Override the translation service to use your wrapper to make a decision on what translation to use.

By no means am I saying it's easy but I think using the translation component, authentication as a director and the service container you can get what you want and not muddle your code base.

You have 2 options:

  1. use Symfony Forms To create 2 form classes, and in your controller, you set the appropriate form class to a twig variable then in your template you render

```

{{ form_start(form) }}
    {{ form_errors(form) }}
    {{ form_row(form.field1) }}
    {{ form_row(form.field2) }}
{{ form_end(form) }}

```

Doing it this way allows you to define the form that displays depending on who is viewing it. You can then define in your services config the method to call from your controller to set this class before the Controller action is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM