How to create a new form in Symfony 2

Hi guys! Today I want to explain how to create a new form in Symfony 2.6. The Symfony Framework has a form component that makes dealing with forms easy. I will explain to you how you can create a form in Symfony by following Symfony2's documentation.

To create a new form, you must first create a new entity:

namespace AppBundle\Entity;

class Task
protected $task;
protected $dueDate;

public function getTask()
return $this->task;

public function setTask($task)
$this->task = $task;

public function getDueDate()
return $this->dueDate;

public function setDueDate(\DateTime $dueDate = null)
$this->dueDate = $dueDate;

Next, add create a new action in your 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'))

return $this->render('Default/new.html.twig', array(
'form' => $form->createView(),

And add

use AppBundle\Entity\Task; // task is the name of your entity
use Symfony\Component\HttpFoundation\Request;

at the top of yoour Controller.

And in your views file add this code:

{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

Don't forget to modify your routing file!

Video tutorial:

Leave a Comment