Member-only story

Simple Input Validation with Symfony Live Components

Stefan Pöltl

If you’re going to have some really small forms in your application, maybe up to 2 or 3 fields, it’s easier to avoid building a Symfony Form. For this usecase there is a really cool Symfony Live Components feature:

The ValidatableComponentTrait is your friend!

Let’s code a Symfony Live Component to submit an email field:

bin/console make:twig-component --live

The PHP Live component code (src/Twig/Components/SaveEmailForm.php):

<?php

namespace App\Twig\Components;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\UX\LiveComponent\ValidatableComponentTrait;

#[AsLiveComponent]
class SaveEmailForm extends AbstractController
{
use DefaultActionTrait;
use ValidatableComponentTrait;

#[LiveProp(writable: true)]
#[Assert\NotBlank(message: 'Please enter a e-mail address')]
#[Assert\Email(message: 'Please enter a valid e-mail address')]
public ?string $email = null;

#[LiveAction]
public function saveAction(): void
{…

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Stefan Pöltl
Stefan Pöltl

No responses yet

Write a response