How to handle a form from another controller in Symfony2?

I have 2 separate controllers Controller1:somethingActionand Controller2:processForm.

As somethingActionI create a form and set its action (url) in the processFormurl. When a form is displayed in the view somethingAction, the POST data goes to processForm.

In processFormI create the same form, validate it and process it. Everything works fine, except when the form is invalid. Since in order to show errors, as well as user input, you will need to display exactly the same view as somethingAction.

It seems to me that I cannot reuse such forms without copying the code (part of the process form), even if it is 3-4 lines, I would expect such functionality to exist.

Is there an easy way to do this? Without AJAX. Did I miss something?

This can be done if the embed controllers can redirect.

+3
source share
1 answer

Two things that might help:

1) Scroll down to “Create Form Classes” in documents to avoid duplicate forms:

http://symfony.com/doc/current/book/forms.html#creating-form-classes

2) The usual template (I would say in many cases it is better to say) should send to the same controller action that generates the form initially. That is, Controller1:somethingActionPOST before Controller1:somethingAction. Then you need some logic (basically an IF statement) that determines when the form was submitted, either processes the form, or displays it with errors. In pseudocode, it might look like this:

function somethingAction()
    if form.isValid()
        process form
        redirect or render a success screen
    else
        render form (with or without errors)
0

All Articles