Symfony Forms Cookbook
Basic form building
Build a form object and render it in a template from within a controller:[1]
// src/AppBundle/Controller/DefaultController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use AppBundle\Entity\Task;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
public function newAction(Request $request)
{
// create a task and give it some dummy data for this example
$task = new Task();
$task->setTask('Write a blog post');
$task->setDueDate(new \DateTime('tomorrow'));
$form = $this->createFormBuilder($task)
->add('task', 'text')
->add('dueDate', 'date')
->add('save', 'submit', array('label' => 'Create Task'))
->getForm();
return $this->render('Default/new.html.twig', array(
'form' => $form->createView(),
));
}
}
Render a form
After passing a form "view" object to a Twig template, the form can be rendered with form helper functions:[2]
{# app/Resources/views/Default/new.html.twig #}
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
Handling form submissions
In the controller, the form object translates user data submitted with the form.[3]
public function newAction(Request $request)
{
// just setup a fresh $task object (remove the dummy data)
$task = new Task();
$form = $this->createFormBuilder($task)
->add('task', 'text')
->add('dueDate', 'date')
->add('save', 'submit', array('label' => 'Create Task'))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action, such as saving the task to the database
return $this->redirect($this->generateUrl('task_success'));
}
// ...
}
- When the page is first loaded, the form is created and rendered.
handleRequest()recognizes that the form was not submitted and does nothing.isValid()returnsfalseif the form was not submitted.
- When the form is submitted,
handleRequest()translates the datahandleRequest()updates the corresponding properties of the entity object ($taskin this case) with the form data.isValid()returnsfalseif the form data isn't valid.- Execution skips that block where the data would be processed, and instead goes to the original view, which is rendered with the submitted form data and error messages.
Notes
- ↑ Building The Form, Symfony forms documentation
- ↑ Rendering The Form, Symfony forms documentation
- ↑ Handling Form Submissions, Symfony forms documentation