chieroz chieroz - 1 year ago 166
PHP Question

Forms with Symfony 3

I am struggling with forms in Symfony 3.

The setup is pretty simple.

A. controller in /src/AppBundle/Controller/Admin/MovieAdminController.php

namespace AppBundle\Controller\Admin;

use AppBundle\Form\MovieFormType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

* @Route("/admin")
class MovieAdminController extends Controller

* @Route("/movie/new", name="admin_movie_new")
public function newAction(Request $request)
$form = $this->createForm(MovieFormType::class);


if ($form->isSubmitted() && $form->isValid()) {

return $this->render('admin/movie/new.html.twig', [
'movieForm' => $form->createView()

B. formtype in /src/AppBundle/Form/MovieFormType.php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MovieFormType extends AbstractType
public function buildForm(FormBuilderInterface $builder, array $options)

public function configureOptions(OptionsResolver $resolver)



C. twig template:

{{ form_start(movieForm) }}
{{ form_widget(movieForm) }}

<button type="submit" class="btn btn-primary">Save</button>

{{ form_end(movieForm) }}

When I submit the form I keep getting the dreadful message "The CSRF token is invalid. Please try to resubmit the form."

The form does have the hidden field with the token, but it seems to me that the submitted value is different from the value in session.

in the profiler I see:

POST Parameters

movie_form [ title => blabla, genre => blabla, budget => 123, _token => e-zvG9Gk0qBJzTE4exIK3K5katq9-_AFEAWyTptx7rg ]

SESSION Parameters

_csrf/movie_form QxbBQISsIwQLUlwWwAPa_l2xZbB5zqdHOwaOxrNAHtg

thank you for your help

Answer Source

I was able to solve my problem.

All was due to Symfony session handling. I am working with a Vagrant VM (Debian Jessie) and the standard setting in app/config/config.yml does not work (see this issue on Github).

It's only one little change: search the line

handler_id:  session.handler.native_file

and change it to

handler_id:  ~

And everything started working 100%.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download