Forms
Maps HTTP request data to a model object (often an entity), runs validation, and renders the HTML.
- Define a FormType class describing each field, its options, constraints, and validation.
- `$form->handleRequest($request)` populates the bound model from POST/PUT data.
- `$form->isSubmitted() && $form->isValid()` is the canonical guard before persisting.
- Data transformers convert between view (string) and model (object/scalar) representations.
- Form events (`PRE_SET_DATA`, `PRE_SUBMIT`, `POST_SUBMIT`) let you build dynamic forms (dependent dropdowns).
- Render with Twig's form helpers: `form_start`, `form_widget`, `form_row`, `form_end`.
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $b, array $options): void
{
$b->add('email', EmailType::class, ['constraints' => [new Email(), new NotBlank()]]);
}
public function configureOptions(OptionsResolver $r): void
{
$r->setDefaults(['data_class' => User::class]);
}
}
Common gotchas
- CSRF protection is enabled by default — disable per-form only when the form is read-only or external.
- If your view shows old data after submit, you probably forgot to redirect after a successful POST (POST/redirect/GET pattern).