Wednesday, February 9, 2011

Form naming

Here is a short note, never forget to give your Form a name when calling Form::create:
# inside your controller

    public function formAction()
    {
        $context = $this->get('form.context');
        $request = $this->get('request');

        $form = MyForm::create($context, 'myform'); // 2nd parameter is the name of the form
        $form->bind($request);
  
        
        return $this->render('MyBundle:Index:form.html.twig', array(
            'form' => $form
        ));
    }

If you forget to pass a name the automatic token check will report everytime an error after submission.

2 comments:

  1. what form.context is it for?, I can figure out that it's a DIC class but can't guess how is linked to a form.
    Thanks.

    ReplyDelete
  2. The form.context (described here: https://github.com/symfony/symfony-docs/blob/master/guides/forms/overview.rst) contains default options and validators used in the form. If you use the default form.context you have automatically a crsf protection in your form, you can check this by the hidden field _token in your form output.

    ReplyDelete