Symfony: 11 – Forms

The best practice is to build the form in a separate, standalone PHP class, which can then be reused anywhere in your application. This new class contains all the directions needed to create the task form. It can be used to quickly build a form object in the controller.

// src/AppBundle/Form/Type/TaskType.php
namespace AppBundle\Form\Type;
 
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
 
class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('task')
            ->add('dueDate', null, array('widget' => 'single_text'))
            ->add('save', 'submit');
    }
 
    public function getName()
    {
        return 'task';
    }
}
 
// Build the form
// src/AppBundle/Controller/DefaultController.php
 
// add this new use statement at the top of the class
use AppBundle\Form\Type\TaskType;
 
public function newAction()
{
    $task = ...;
    $form = $this->createForm(new TaskType(), $task);
 
    // ...
}

Every form needs to know the name of the class that holds the underlying data (e.g. AppBundle\Entity\Task). Usually, this is just guessed based off of the object passed to the second argument to createForm (i.e. $task). While not always necessary, it’s generally a good idea to explicitly specify the data_class option by adding the following to your form type class:

use Symfony\Component\OptionsResolver\OptionsResolverInterface;
 
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Task',
    ));
}

When mapping forms to objects, all fields are mapped. Any fields on the form that do not exist on the mapped object will cause an exception to be thrown. In cases where you need extra fields in the form that will not be mapped to the underlying object, you need to set the mapped option to false. Additionally, if there are any fields on the form that aren’t included in the submitted data, those fields will be explicitly set to null. The field data can be accessed in a controller with $form->get(‘dueDate’)->getData();. In addition, the data of an unmapped field can also be modified directly $form->get(‘dueDate’)->setData(new \DateTime());

use Symfony\Component\Form\FormBuilderInterface;
 
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('task')
        ->add('dueDate', null, array('mapped' => false))
        ->add('save', 'submit');
}