0

EDIT: There is a Tl;Dr at the end...

I keep getting CSRF errors while using symfony2 and auto generated forms.

Here's my controller: (new is called to display form, create is called on submit)

public function newAction($guru)
{

    //Make the Entity Manager
    $em = $this->getDoctrine()
            ->getEntityManager();
    $guru = $em->getRepository('TSNStatsBundle:Guru')
            ->findOneById($guru);
    //If the guru id exists        
    if ($guru)
    {
        $alert = new Alert();
        //Create default values
        $time = new \DateTime(2012-12-30);
        $time->setTime(23,59);

        //Set default times to "none available (23:59)"
        $alert->setText($time)
        ->setEmail($time)
        ->setTwitter($time)
        ->setChat($time)
        ->setGuru($guru);

        //Make the form, set types, 
        $formBuilder = $this->createFormBuilder($alert);


         $formBuilder->add('buy', 'checkbox', array(
                    'required' => false
                ))
                ->add('date', 'date', array(
                    'input' => 'datetime',
                    'widget' => 'single_text'
                ))
                ->add('stock', new StockType());
        if ($guru->getInstantAlerts() ==1)
        {
            if ($guru->getText() == 1)
            {
                $formBuilder->add('text', 'time', array(
                       'input' => 'datetime',
                       'widget' => 'text',

                   ));
            }
            if ($guru->getEmail() == 1)
            {
                $formBuilder->add('email', 'time', array(
                       'input' => 'datetime',
                       'widget' => 'text',

                   ));
            }
            if ($guru->getTwitter() == 1)
            {
                $formBuilder->add('twitter', 'time', array(
                       'input' => 'datetime',
                       'widget' => 'text',

                   ));
            }
            if ($guru->getChat() == 1)
            {
                $formBuilder->add('chat', 'time', array(
                       'input' => 'datetime',
                       'widget' => 'text',

                   ));
            }
        }
        $formBuilder->add('size')
                ->add('short', 'checkbox', array(
                    'required' => false
                ))
                ->add('his')
                ->add('guru');
         $form = $formBuilder->getForm();



        return $this->render('TSNStatsBundle:Buy:new.html.twig', array(
            'form' => $form->createView(),
            'guru' => $guru
        ));



    }
    else
    {
        //your guru ain't real bro!
    }
    return $this->render('TSNStatsBundle:Buy:new.html.twig', array(
        'alert' => $alert,
        'form' => $form->createView(),
        'guru' => $guru->getName()

     ));
}

public function createAction()
{
    $alert = new Alert();

    $form = $this->createForm(new AlertType(), $alert);
    $request = $this->getRequest();
    if ($this->getRequest()->getMethod() == 'POST') {
        $form ->bind($request);


        if ($form->isValid())
        {
            $em = $this->getDoctrine()
                    ->getEntityManager();
            $em->persist($alert);
            $em->flush();

            return $this->redirect($this->generateUrl('new_alert', array(
                'guru' => 2
            ) ));

        }
    }

    return $this->render('TSNStatsBundle:Buy:errors.html.twig', array(
          'errors' => $form->getErrors()
    ));

}

Here's my template:

Adding entry for {{ guru }}
<form action="{{ path('create_alert' ) }}" method="post" {{ form_enctype(form) }} class="alert">
{{ form_widget(form) }}
<p>
    <input type="submit" value="Submit">
</p>
</form>

As far as I can tell, everything is by the book. A _token value IS in every form every time I refresh, the widget it getting called, so all parts should be there...

Thanks,

EDIT: when I replace my whole form creation process with:

$form = $this->createForm(new AlertType(), $alert);

then it works again. The problem is the logic I want doesn't belong in a "type" class. That and the fact that the way I'm doing it SHOULD work right? Could it have anything to do with the way I'm adding elements to my form? That's the only thing I see different about my build vs. a createForm() build.

Tl;Dr: Using a createForm call with an *entity*Type call works fine, creating my own form using createFormBuilder() gets met with a CSRF error on every submit.... Same _token is used for both.

Maveric
  • 99
  • 1
  • 6
  • May be a strange question, but do sessions work? The token is generated from the form's id and the session's id, if you get a new session id every pageview, that may present itself like this. – Maerlyn Dec 31 '12 at 10:15
  • I haven't messed around with sessions yet. I'm converting an existing site over to symfony and learning as I go, but the fact that I found out it works when I use createForm call makes me think that's not the issue. – Maveric Dec 31 '12 at 13:52
  • Did you confirmed that there's no hidden input tags in the output html? – denkiryokuhatsuden Sep 05 '13 at 07:47
  • 1
    Possible duplicate of [The CSRF token is invalid. Please try to resubmit the form](http://stackoverflow.com/questions/23455780/the-csrf-token-is-invalid-please-try-to-resubmit-the-form) – M Khalid Junaid Jan 13 '16 at 17:35

3 Answers3

2

maybe using this will help you :

{{form_widget(form._token)}}
parisssss
  • 803
  • 16
  • 36
  • Thanks for this! I'd tried multiple hard-wired variations on the theme, e.g., ``, but this is the one that made the difference. – geoB Nov 19 '14 at 22:58
1

Try substituting

{{ form_widget(form) }}
{{ form_rest(form) }}

For

{{ form_widget(form) }}
gview
  • 14,876
  • 3
  • 46
  • 51
  • I had tried that too. The form_widget(form) calls form_rest though.. I DO have a "_token" hidden field in my form. – Maveric Dec 31 '12 at 02:49
0

You can pass the same $options array like in the form type, to a FormBuilder, and you can turn csrf protection off this way:

$this->createFormBuilder($object, $options = array(
    'csrf_protection' => false,
));

Original example: http://symfony.com/doc/current/book/forms.html#csrf-protection

hattila
  • 490
  • 5
  • 13