pitch/form

Form action

Installs: 202

Dependents: 0

Suggesters: 0

Security: 0

Stars: 1

Watchers: 2

Forks: 0

Open Issues: 0

Type:symfony-bundle

v1.2.0 2022-06-22 09:29 UTC

This package is auto-updated.

Last update: 2024-10-22 15:04:05 UTC


README

Streamlined controllers handling form input.

Usage

Annotate controller

Keep creating and handling the form input out of your controller by annotating it with the desired FormType.

namespace App\Controller;

use App\Form\MyFormType;
use Pitch\Form\Form;

class MyController
{
    #[Form(MyFormType::class)]
    public function __invoke($data)
    {
        // Just handle the data of a valid form.
        // If the form is not submitted yet or the input is invalid,
        // the controller will not be called and the
        // Symfony\Component\Form\FormInstance will be returned.
    }
}

This also supports Doctrine Annotations if installed.

Handle FormInstance controller return

Symfony requires controllers to return a Symfony\Component\HttpFoundation\Response. But you can convert other return values (like the FormInstance) on the kernel.view event. Add your own EventSubscriber or add a ResponseHandler with pitch/symfony-adr.

Use the form inside the controller

Just like the data for valid forms the FormInstance is made available to the controller per [Request attributes])https://symfony.com/doc/current/components/http_foundation.html#accessing-request-data). Symfony's RequestAttributeValueResolver injects them into the controller if there is a parameter with the same name as the attribute. The attribute names default to just data and form, but in case of conflicts you could provide others per annotation.

namespace App\Controller;

use App\Form\MyFormType;
use Pitch\Form\Form;
use Symfony\Component\Form\FormInterface;

class MyController
{
    #[Form(
        MyFormType::class,
        dataAttr: 'myData',
        formAttr: 'myForm',
    )]
    public function __invoke(
        Request $request,
        FormInterface $myForm,
        $myData,
    ) {
    }
}

You can prevent the automatic return of invalid or unsubmitted forms per annotation #[Form(MyFormType::class, returnForm: false)] or per config parameter pitch_form.returnForm: false.

Use data entities

namespace App\Controller;

use App\Form\MyFormType;
use App\Form\MyFormEntity;
use Pitch\Form\Form;

class MyController
{
    #[Form(
        MyFormType::class,
        entity: MyFormEntity::class,
    )]
    public function __invoke(MyFormEntity $data)
    {
    }
}

If the entity can not be created by just calling the constructor, you can register a factory implementing Pitch\Form\FormEntityFactoryInterface as a service.

namespace App\Controller;

use App\Form\MyFormType;
use App\Form\MyFormEntity;
use Pitch\Form\Form;

class MyController
{
    #[Form(
        MyFormType::class,
        entityFactory: 'myFactoryId',
    )]
    public function __invoke(MyFormEntity $data)
    {
    }
}