Home > database >  Rendering form via Ajax - Symfony 5
Rendering form via Ajax - Symfony 5

Time:01-05

Up to Symfony 4, I used to load a form, via Ajax, returning something like this:

$result = $this->renderView('my/template.html.twig',[
    'form' => $form->createView()
]);
return new Response($result);

Since Symfony 5, this is not working anymore. I tried every posible combination using $this->renderForm(), $this->render() and 'form'=>$form, with no success. What's the trick?

CodePudding user response:

Hi you can render form like this

public function __invoke()
{
    return $this->render('my/template.html.twig', [
        'form' => $form->createView()
    ]);
}

Note:

render() -> will return Response object

renderView() -> will return string (rendered twig template)

CodePudding user response:

Try with

return new JsonResponse(['view' => $this->render('path/to_view.html.twig')->getContent()]);

It will return a json response to your Ajax call. You can access to 'view' key (name it as you want) which contain the html content of the page rendering [$this->render()->getContent]. This is the way I use in my Symfony 5.4 project.

  •  Tags:  
  • Related