Skip to content

Create Symfony forms at record speed using PHP 8 attributes!

License

Notifications You must be signed in to change notification settings

ansien/RapidFormBundle

Repository files navigation

RapidFormBundle - Create Symfony forms at record speed using PHP 8 attributes!

Latest Version on Packagist Total Downloads GitHub

Example

The goal of this bundle is to make it possible to build Symfony forms using PHP 8 attributes on your DTO.

The problem

Making forms in Symfony is fairly simple. But once you start using DTO's there will always be two classes you'll have to maintain: your DTO and your Symfony form type. This is not ideal because it creates unnecessary work, maintenance and can also easily lead to bugs.

The solution

This bundle will significantly speed up the creation of forms inside your Symfony application. With the provided PHP 8 attributes you can quickly build forms by decorating your DTO and you won't have to maintain two different classes anymore.

Installation

You can install the package via Composer:

composer require ansien/rapid-form-bundle

Usage

Form

<?php

declare(strict_types=1);

namespace App\Form;

use Ansien\RapidFormBundle\Attribute\Form;
use Ansien\RapidFormBundle\Attribute\FormField;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Validator\Constraints as Assert;

#[Form]
class ExampleForm
{
    #[FormField(TextType::class, [
        'required' => true,
    ])]
    #[Assert\NotBlank]
    public ?string $name = null;

    #[FormField(TextType::class)]
    public ?string $description = null;
}

Controller

<?php

declare(strict_types=1);

namespace App\Controller;

use Ansien\RapidFormBundle\Form\RapidFormBuilderInterface;
use App\Form\ExampleForm;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class ExampleController extends AbstractController
{
    public function __construct(private RapidFormBuilderInterface $formBuilder) 
    {
    }

    #[Route('/example', methods: ['GET', 'POST'])]
    public function __invoke(Request $request): Response
    {
        $data = new ExampleForm();
        $form = $this->formBuilder->create($data)->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // Do something with $data
        }
        
        return $this->render('example.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}

See ./examples for more examples.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Supporters

Stargazers repo roster for @ansien/RapidFormBundle

Credits

License

The MIT License (MIT). Please see License File for more information.