In this tutorial we will look at two examples of using forms in Symfony 2. In the the first, we will place form elements straight in the View file and then handle the form processing manually in the controller. In the second, we’ll use the Symfony form system to declare forms in an object oriented way and have Symfony process and persist the values.
We will be working on a simple installation of the Symfony framework. As you may know, it comes with a default bundle called AcmeDemoBundle
and we will use that to illustrate working with forms. All the final code can be found in this repository I set up for this tutorial. Feel free to follow along or take a peek at the final code.
Non-entity forms
The first example we will look at is how to process forms declared as regular html elements inside of a Symfony View file. There are 3 steps we will take to illustrate this:
- We will create a View file that contains our form html
- We will create a new Controller method in the
WelcomeController
class calledform1Action
that will handle our business logic (rendering the View, processing the form, etc). - We will then create a simple route entry to map a URL path to this method so that we can see the form in the browser and be able to submit it.
Let’s first create the View file that will show our form and the submitted value on top. In a file called form1.html.twig
located in the src/Acme/DemoBundle/Resources/views/Welcome
folder (the corresponding folder for the Welcome
controller class Symfony comes with by default) I have the following:
{% extends "AcmeDemoBundle::layout.html.twig" %}
{% block content %}
Form values
{% if name is defined %}
Name: {{ name }}
{% endif %}
{% endblock %}
Above, I am extending the default layout in the
DemoBundle
just so I don’t see a very white page. And the rest is pretty basic as well: declaring a simple html form that posts to itself and showing the value of the only text field above the form (which will be passed from the Controller after processing in a variable called name
).
Next, let’s declare the Controller method in charge of displaying this View and processing the form inside it. In the WelcomeController
class file, I do two things:
Continue reading %Building and Processing Forms in Symfony 2%
more
{ 0 comments... » Building and Processing Forms in Symfony 2 read them below or add one }
Post a Comment