Working with forms in Symfony framework (Lesson 12. Forms. Introduction)

In this note we will learn how to create and handle forms in Symfony framework.

Forms can be created "from scratch" or using an ORM (object-relational mapping) to generate forms based on database tables. Let's start by exploring the second option. In practice, these types of forms are most commonly encountered since in most cases, the data entered in the form needs to be stored somewhere (in a database).

In the simplest case, you first need to create an instance of the model. This instance will be needed by the form builder's constructor (Form Builder). Then you need to enumerate the fields. Here's how it looks like (inside a controller):

// src/Acme/TaskBundle/Controller/DefaultController.php
namespace AcmeTaskBundleController;
use SymfonyBundleFrameworkBundleControllerController;
use AcmeTaskBundleEntityModel;
use SymfonyComponentHttpFoundationRequest;
class DefaultController extends Controller
{
  public function newAction(Request $request)
   {
    $model = new Model();
    $model->setField('Some value');
    $model->setDueDate(new DateTime('tomorrow'));
    $form = $this->createFormBuilder($model)
      ->add('field', 'text')
      ->add('dueDate', 'date')
      ->getForm();
   return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
     'form' => $form->createView(),
     ));
  }
}
Next, the template:
{# src/Acme/TaskBundle/Resources/views/Default/new.html.twig #}
<form action="{{ path('task_new') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
 <input type="submit" />
</form>
Please note the arguments of the add($field, $type) method. The first argument is the field name and the second argument is the field type (which can be any standard HTML type such as text, textarea, password, ...) plus some special Symfony types (date, email, birthday, etc. For a complete list, refer to this link).

Handling forms in Symfony framework requires minimal additional code:

// src/Acme/TaskBundle/Controller/DefaultController.php
namespace AcmeTaskBundleController;
use SymfonyBundleFrameworkBundleControllerController;
use AcmeTaskBundleEntityModel;
use SymfonyComponentHttpFoundationRequest;
class DefaultController extends Controller
{
  public function newAction(Request $request)
   {
    $model = new Model();
    $model->setField('Some value');
    $model->setDueDate(new DateTime('tomorrow'));
    $form = $this->createFormBuilder($model)
      ->add('field', 'text')
      ->add('dueDate', 'date')
      ->getForm();
   if ($request->isMethod('POST')) {
     $form->bind($request);
      if ($form->isValid()) {
     // Here you handle the data, for example, saving it in the database:
       $em = $this->getDoctrine()->getManager();
       $em->flush();
     }
   return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
     'form' => $form->createView(),
     ));
  }
}
To customize a form in Symfony framework, you can add class or id attributes to fields:
add('position', 'number', array('label' => 'Position',
                    'attr' => array('class' => 'class_name')))
We also changed the label (by default, the label is the same as the field name in the database table).

So, we have covered the simplest case. Now we can create a basic form that allows us to modify values in the corresponding fields of a database table.