Disable symfony 2 csrf token protection on ajax submit
If you're looking for a bit easier and faster solution than suggested in answer above, here's how:
<?php
// ...
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\OptionsResolver\OptionsResolver;
class MyType extends AbstractType
{
// ...
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'csrf_protection' => false,
));
}
}
.. or if you're using older versions (Symfony 2.0.*):
<?php
// ...
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class MyType extends AbstractType
{
// ....
public function getDefaultOptions(array $options)
{
$options = parent::getDefaultOptions($options);
$options['csrf_protection'] = false;
return $options;
}
}
Consult the Symfony documentation for additional information.
Edit: updated answer to latest Symfony version, thanks naitsirch
Using the form factory
For those who want to create a simple form in a controller:
$form = $this->container->get('form.factory')
->createNamedBuilder(null, 'form', null, array('csrf_protection' => false))
->add('yourField','text', array(
'label' => false,
'mapped' => false
))
->getForm();
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'csrf_protection' => false,
]);
}