Showing posts with label form. Show all posts
Showing posts with label form. Show all posts

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.

Translate form labels inside Twig templates

In this exmaple I assume you've a configured transaltion service up and running. This tip works when you're iterate over loops, like in this example and/or when you print everything out by hand ({{ form_label(form.my_field, label) }}).
{% block someblock %}
    <form action="#" method="post" {{ form_enctype(form) }}>
        {{ form_errors(form) }}

        {% for field in form %}
            {% if not field.ishidden %}
                <div>
                    <!-- translates the field name (stored in key) and saves it in the variable label -->
                    {% set label %}{% trans field.key %}{% endset %}   
                    
                    <!-- passes the translated name as the second parameter for your own label -->
                    {{ form_label(field, label) }}

                    {{ form_errors(field) }}
                    {{ form_field(field) }}
                </div>
            {% endif %}
        {% endfor %}

        {{ form_hidden(form) }}
        <input type="submit" />
    </form>
{% endblock %}