A form gives the user a way to change data in your application, in a structured way. To mutate a simple array
of data, we create a form using a form builder:
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
// ...
function myAction (Request $request) {
$data = array(
'value' => null,
'number' => 10,
'string' => 'No value',
);
$form = $this->createFormBuilder($data)
->add('value', TextType::class, array('required' => false))
->add('number', NumberType::class)
->add('string', TextType::class)
->add('save', SubmitType::class)
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// $data is now changed with the user input
// Do something with the data
}
return $this->render(..., array(
'form' => $form->createView(),
// ...
));
}
In your template, render your form using the form(...)
Twig function:
{# Render the form #}
{{ form(form) }}
It will, without styling, look something like below:
The labels, IDs, names and form tags are generated automatically. By default, the form submits to the current page with a POST request.