8

I used the code below and it has csrf too. But how can I disable its csrf? I searched and Disable CSRF token on login form did not help, as there createFormBuilder() is not used in my case below, so what should I do?

$csrfStorage = new NativeSessionTokenStorage();
$csrfGenerator = new UriSafeTokenGenerator();
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);

$formFactory = Forms::createFormFactoryBuilder()
    ->addExtension(new CsrfExtension($csrfManager))
    ->getFormFactory();


$defaultFormTheme = 'bootstrap_3_layout.html.twig';

$vendorDir = realpath(__DIR__.'/../vendor');
$appVariableReflection = new \ReflectionClass('\Symfony\Bridge\Twig\AppVariable');
$vendorTwigBridgeDir = dirname($appVariableReflection->getFileName());
$viewsDir = realpath('twig');

$twig = new Twig_Environment(new Twig_Loader_Filesystem(array(
    $viewsDir,
    $vendorTwigBridgeDir.'/Resources/views/Form',
)));
$formEngine = new TwigRendererEngine(array($defaultFormTheme), $twig);
$twig->addRuntimeLoader(new \Twig_FactoryRuntimeLoader(array(
    TwigRenderer::class => function () use ($formEngine, $csrfManager) {
        return new TwigRenderer($formEngine, $csrfManager);
    },
)));
$twig->addExtension(new FormExtension());

$translator = new Translator('en');
$twig->addExtension(new TranslationExtension($translator));
$form = $formFactory->createBuilder()
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->getForm();

$request = Request::createFromGlobals();
$form->handleRequest();
if ($form->isSubmitted() && $form->isValid()) {
    $data = $form->getData();
    print_r($data);
}

$twig->display('new.html.twig', array(
    'form' => $form->createView(),
));
Joe Hark
  • 155
  • 1
  • 3
  • 10
  • Update your builder part to `createBuilder('', null, ['csrf_protection' => false])` – Mert Öksüz Nov 12 '17 at 14:21
  • 1
    I get Error 0: Could not load type "". I guess because first parameter cannot be null? what should I pass into it? – Joe Hark Nov 12 '17 at 14:49
  • You should pass FormType, your own formtype which you created. – Mert Öksüz Nov 12 '17 at 14:50
  • If you want to disable csrf for everything then set config.yml framework csrf_protection to false. But I really don't understand why you are adding the csrf manager if you don't want csrf protection. – Cerad Nov 12 '17 at 15:47

2 Answers2

16
$form = $formFactory->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', null,  array('csrf_protection' => false))
Mohamed Ben HEnda
  • 2,686
  • 1
  • 30
  • 44
6

To disable it globally for all of the forms (if for example you want to implement your own logic)

You can set in your config/packages/framework.yaml

framework:
  form:
    csrf_protection:
      enabled: false
Tofandel
  • 3,006
  • 1
  • 29
  • 48