pitch/liform

Transform Symfony Forms into Json Schema

Installs: 239

Dependents: 0

Suggesters: 0

Security: 0

Stars: 3

Watchers: 1

Forks: 0

Open Issues: 2

Type:symfony-bundle

v1.1.2 2021-06-14 05:47 UTC

This package is auto-updated.

Last update: 2024-12-21 17:07:05 UTC


README

codecov

Liform

Library for transforming Symfony Form Views into JSON.

It is developed to be used with liform-react-final, but can be used with any form rendering supporting JSON schema.

Installation

Install per Composer from Packagist.

composer require pitch/liform

If you execute this inside a Symfony application with Symfony Flex, LiformInterface will be available per Dependency Injection right away.

Basic usage

$form = \Symfony\Component\Form\Forms::createFormFactory()->create();
$form->add('foo', \Symfony\Component\Form\Extension\Core\Type\TextType::class);
$form->add('bar', \Symfony\Component\Form\Extension\Core\Type\NumberType::class);

/* ... handle the request ... */

$resolver = new \Pitch\Liform\Resolver();
$resolver->setTransformer('text', new \Pitch\Liform\Transformer\StringTransformer());
$resolver->setTransformer('number', new \Pitch\Liform\Transformer\NumberTransformer());
/* ... */

$liform = new \Pitch\Liform\Liform($resolver);
$liform->addExtension(new \Pitch\Liform\Extension\ValueExtension());
$liform->addExtension(new \Pitch\Liform\Extension\LabelExtension());
/* ... */

return $liform->transform($form->createView());

Inside a Symfony application

namespace App\Controller;

/* use statements */

class MyFormController extends Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{
   protected LiformInterface $liform;

   /* Let the service container inject the service */
   public function __construct(LiformInterface $liform)
   {
      $this->liform = $liform;
   }

   public function __invoke(Request $request)
   {
      $form = $this->createForm(MyFormType::class);
      $form->handleRequest($request);
      if ($form->isSubmitted() && $form->isValid()) {
         /* ... do something ... */
      } else {
         return new Response($this->render('my_form.html.twig', [
            'liform' => $this->liform->transform($form->createView()),
         ]), $form->isSubmitted() ? 400 : 200);
      }
   }
}

The result

The TransformResult is an object that when passed through json_encode() will produce something like:

{
   "schema": {
      "title": "form",
      "type": "object",
      "properties": {
         "foo": {
            "title": "foo",
            "type": "string"
         },
         "bar": {
            "title": "bar",
            "type": "number",
         }
      },
      "required": [
         "foo",
         "bar"
      ]
   },
   "meta": {
      "errors": {
         "foo": ["This is required."]
      }
   },
   "values": {
      "bar": 42
   }
}

Acknowledgements

This library is based on Limenius/Liform. Its technique for transforming forms using resolvers and reducers is inspired by Symfony Console Form.