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
- 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.
Creating reusable forms is discussed, and how to separate our form logic from our controller.
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!