Lesson 6 of 9 · 24m
Forms, Twig, and Validation: Boring on Purpose
Server-rendered forms done properly: CSRF, validation groups, Twig escaping, uploads, errors, and progressive enhancement without frontend churn.
Not every application needs a JavaScript framework argument. Symfony Forms and Twig remain one of the fastest ways to build secure administrative and line-of-business interfaces: CSRF protection, validation, escaping, and predictable rendering included.
Forms are objects with boundaries
final class CustomerType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name', TextType::class)
->add('email', EmailType::class)
->add('billingCountry', CountryType::class);
}
}Bind forms to input objects when the user-submittable contract differs from entity invariants. Entities model persistence and consistency; input objects model what this form may ask for.
Validation belongs near the input
final class CustomerInput
{
#[Assert\NotBlank]
#[Assert\Length(max: 120)]
public string $name = '';
#[Assert\Email]
public string $email = '';
}Handle submission explicitly:
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
return $this->redirectToRoute('customer_index');
}isSubmitted() before isValid() matters. Validation on an unsubmitted form is a classic confusing bug.
Twig escapes by default — do not defeat it
<h1>{{ customer.name }}</h1>
{{ customer.notes|raw }} {# dangerous unless trusted and sanitized #}|raw is not formatting; it is a security decision. Rich user HTML needs a real sanitizer and a documented allowlist.
CSRF and uploads are server concerns
Symfony Forms include CSRF tokens automatically. Hand-rolled state changes need explicit token validation and must never be GET links. Uploads require server-side mime, size, and extension validation, generated filenames, and storage outside the web root or in object storage. Client filenames are untrusted input.
Field notes
- Redirect after successful POST so refresh does not resubmit.
- Server-side validation remains mandatory even when browser validation exists.
- Upload failures often happen before PHP: check nginx
client_max_body_sizeand PHPpost_max_sizetogether. - Progressive enhancement is fine; keep POST/redirect/GET working for accessibility, reloads, and back-button behavior.
- Boring server rendering is not technical debt. Unowned complexity is.
Was this lesson helpful?