R
R
redguard2016-02-29 10:11:48
symfony
redguard, 2016-02-29 10:11:48

How to properly embed a form in a symfony 3 template?

Sat down to study symphonies. I'm making a simple page with an embedded form.
I have a page controller.
There is a page template.
I have a form template.
I save the result of createForm to the $form variable
$form = $this->createForm(SendForm::class);
and add it to the page template like this

return $this->render(
            'account/account.html.twig',
            array(
                'user_name' => $userName,
                'send_form' =>$form // Передаю в шаблон
            )
        );

I get an error
Fatal Error: Object of class Symfony\Component\Form\Form could not be converted to string
\
Next, I tried first to render the form into a variable.
$form = $this->render(
            'account/send_form.html.twig',
            array('form' => $form->createView())
        );

And I got escaped html of the form.
How to properly render the form in order to insert it into the page template?
Controller code:
<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use AppBundle\Form\SendForm;

class AccountController extends Controller {
    /**
     * @Route("/account", name="account")
     */
    public function indexAction(Request $request)
    {

        $userName = "Имя";

        //Создаю форму
        $form = $this->createForm(SendForm::class);
       
        return $this->render(
            'account/account.html.twig',
            array(
                'user_name' => $userName,
                'send_form' =>$form // Передаю в шаблон
            )
        );
        
    }
    
}
?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Vasilenko, 2016-02-29
@redguard

Pass form to template:
Render in twig:

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

A
Alexey Romanenko, 2016-02-29
@slimus

Everything you may need in the early stages about forms and symfony is here: symfony.com/doc/current/book/forms.html You
seem to have everything right (in the case of $form->createView()). What does escaped mean?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question