Forms
| A FormType class | |
| Render in Twig | |
| Handle the request | |
| Check isValid |
A FormType class
Forms start as plain PHP classes, not HTML. A FormType names the fields, their types, and their options inside the buildForm method.
Each add call takes a field name and a type class. TextType renders a text input and SubmitType renders the button, and the same class later drives validation and data mapping.
class ProductType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add("name", TextType::class); $builder->add("save", SubmitType::class); } }
Render in Twig
The controller passes a form view to the template, and three Twig helpers do the rest. The start helper opens the tag with the right method and action.
The widget helper prints every field, and the end helper closes the tag and adds hidden fields. Custom markup can replace the widget line field by field later.
{{ form_start(form) }} {{ form_widget(form) }} {{ form_end(form) }}
Handle the request
Rendering is only half the job: the same form must read the answer. The handleRequest call feeds the current request into the form object.
After that call the form knows whether it was submitted and what data arrived. Unsubmitted forms skip validation and render empty again.
$form->handleRequest($request); if ($form->isSubmitted()) { $product = $form->getData(); }
Check isValid
Submission alone does not mean the data is good. The isValid call runs every constraint and returns true only when all of them pass.
Keep the persist and flush calls inside that check. Invalid forms fall through, and the template re-renders with error messages next to each field.
if ($form->isSubmitted() && $form->isValid()) { $entityManager->persist($product); $entityManager->flush(); }
Next: Validation
Article author: Arthur Isaev