Render controller in TWIG and display form errors

I have indexAction and contactAction

contactAction is a simple fieldless form (FormType), as shown below:

/**
 * @Route("/contact", name="contact")
 * @Template()
 * @param Request $request
 * @return array
 */
public function contactAction(Request $request)
{
    $form = $this->createForm(new ContactType());

    $form->handleRequest($request);

    if ($form->isValid()) {
        $firstName = $form->get('first_name')->getData();
        $lastName = $form->get('last_name')->getData();
        $email = $form->get('email')->getData();
        $message = $form->get('message')->getData();
    }
    return array(
        'form' => $form->createView()
    );
}

and I create this form in my indexAction using this TWIG command:

{{ render(controller('RusselBundle:Default:contact')) }}

Everything is okey, if the page is not reloaded, the HTML validators work fine, but if the form has some errors, such as: firstName length, the error does not appear at all, how can I do this so that the errors appear as indexAction? Any help would be greatly appreciated. I'm just wondering, and if ... how? Sorry for my English....

+4
source share
3 answers

, , . @DebreczeniAndrás, render(controller()), , , ( ).

public function contactAction(Request $request)
{
    $request = $this->get('request_stack')->getMasterRequest();

    $form = $this->createForm(new ContactType());

    //...
}
+5

symfony3 ,

{{ render(controller('RusselBundle:Default:contact', {'request':app.request})) }}
+1

If you use the function renderin your branch, this creates a subquery, so your original values ​​(i.e. in your main request) are lost.

You can submit your main request to the form rendering action as follows:

{{ render(controller('RusselBundle:Default:contact'), 'request' : app.request ) }}

This will bring all the necessary query parameters to your subquery.

0
source

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


All Articles