Symfony 2 Form: A Short Guide

A web form or a HTML form is basically a page that allows a user to enter information that is then sent to a server for processing.

This is a short guide to the Symfony 2 form. Symfony has a very powerful form component that makes using forms simpler when compared to HTML forms, although forms can still be very challenging to get your head around and learn.

Within Symfony there is a standalone form component library that can also be used with other non-Symfony projects.

Symfony 2 gives us a wide range of ways that we can customise how a form is rendered. Form fragments can be used to render just one part of a Symfony 2 form, or to render each part of the form.

Symfony 2 form elements can include:

  • Simple text input
  • Text area
  • Select drop down list
  • Checkboxes
  • Radio buttons
  • File selection
  • Reset button
  • Submit button

Creating a form

We can write recipes with form objects using the form builder. You can also import a form theme to customise your form, or use the default Symfony 2 form theme that comes as standard with Symfony.

When using forms in a template in Symfony, you can use functions (for rendering each bit of the form) and variables (less often used, to obtain any information about any field).

To get started with forms, watch our video on YouTube, an introduction to forms in Symfony 2.

This video covers a range of topics including:

Creating a basic Symfony 2 form

It covers building the form inside our controller and rendering the form in our view.

How to handle the submission of the form back to our controller (where user presses submit).


Rendering your form

There is noob mode that involves pasting it in, and real world mode that is more indepth and where your form gets customised.

Changing the action and method of a form

This covers posting to GET and where your data is being posted to.

Form classes

Creating reusable forms is discussed, and how to separate our form logic from our controller.

Form validation

You shouldn’t trust the raw data input from a user. Symfony provides two methods of form validation, there is the front end and server side. Front end shouldn’t be relied upon and you should ideally always implement server side validation. How to do this is explained.

How to prevent cross site request forgeries (CSRF)

This involves a single line of code and is not as complicated as it may sound.

More resources to learn about the Symfony 2 form:

The best way to learn is by doing so start practicing!

Published by

Code Review

CodeReviewVideos is a video training site helping software developers learn Symfony faster and easier.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.