Search code examples
phpsymfonysymfony4

Create multiple symfony 4 forms in the same view


I have a symfony 4 application that has multiple forms on the same page. However because they use the same formType, only one renders with the correct inputs.

There is one create form, and multiple update forms which are triggered when the user clicks a modal. I render the update forms on the page by calling a twig include then passing the item id into the partial. The partial then renders the same form as the create form but with the values from the passed object.

Is there any way of achieving this?

A basic representation of the current view:

{#create form#}
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

{#update form1#}
{{ form_start(, {'action': path('edit', { "id" : update.id }),  'attr': {'id' : dealer.id}}) }}
{{ form_widget(form) }}
{{ form_end(form) }}

{#update form2#}
{{ form_start(, {'action': path('edit', { "id" : update.id }),  'attr': {'id' : dealer.id}}) }}
{{ form_widget(form) }}
{{ form_end(form) }}

I would like to use the same controller methods for CRUD and have tried creating a Form\AbstractType for each update entity but didn't have any luck!


Solution

  • instead of sending all the forms same name, change to names, formRead, formUpdate, FormDelete etc.. The last $form will override self to one before.

    {% if formRead is defined %}
    {#create form#}
    {{ form_start(formRead) }}
    {{ form_widget(formRead) }}
    {{ form_end(formRead) }}
    {% end if %}
    
    {% if formUpdate is defined %}
    {#update form1#}
    {{ form_start(formUpdate, {'action': path('edit', { "id" : update.id }),  'attr': {'id' : dealer.id}}) }}
    {{ form_widget(formUpdate) }}
    {{ form_end(formUpdate) }}
    {% end if %}