Back to all demos
DEMO

Auto-Validating Form

src/Twig/RegistrationFormComponent.php

use App\Form\RegistrationForm;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentWithFormTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent('registration_form')]
class RegistrationFormComponent extends AbstractController
{
    use ComponentWithFormTrait;
    use DefaultActionTrait;
    #[LiveProp]
    public bool $isSuccessful = false;

    #[LiveProp]
    public ?string $newUserEmail = null;

    protected function instantiateForm(): FormInterface
    {
        return $this->createForm(RegistrationForm::class);
    }

    #[LiveAction]
    public function saveRegistration()
    {
        $this->submitForm();

        // save to the database
        // or, instead of creating a LiveAction, allow the form to submit
        // to a normal controller: that's even better.

        $this->newUserEmail = $this->getFormInstance()
            ->get('email')
            ->getData();
        $this->isSuccessful = true;
    }
}

templates/components/registration_form.html.twig

<div
    {{ attributes }}
>
    {% if isSuccessful %}
        <div>Welcome {{ newUserEmail}}!</div>
    {% else %}
        <form
            novalidate
            data-action="live#action"
            data-action-name="prevent|saveRegistration"
            data-model="on(change)|*"
        >
            {{ form_row(form.email) }}
            {{ form_row(form.password) }}
            {{ form_row(form.terms) }}

            <button type="submit" class="btn btn-primary">Register</button>

            {{ form_rest(form) }}
        </form>
    {% endif %}
</div>

Type an invalid email and watch as it auto-validates when you leave the field!