pitch/liform

将 Symfony 表单转换为 Json Schema

安装: 238

依赖项: 0

建议者: 0

安全: 0

星级: 3

关注者: 1

分支: 0

开放问题: 2

类型:symfony-bundle

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

This package is auto-updated.

Last update: 2024-09-21 16:38:38 UTC


README

codecov

Liform

一个库,用于将 Symfony 表单视图 转换为 JSON。

它旨在与 liform-react-final 一起使用,但也支持任何支持 JSON schema 的表单渲染。

安装

通过 ComposerPackagist 安装。

composer require pitch/liform

如果您在 Symfony 应用程序中执行此操作,并使用 Symfony Flex,则 LiformInterface 将会通过 依赖注入 立即可用。

基本用法

$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());

在 Symfony 应用程序内部

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);
      }
   }
}

结果

TransformResult 是一个对象,当通过 json_encode() 传递时,将产生类似以下内容:

{
   "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
   }
}

致谢

此库基于 Limenius/Liform。它使用解析器和还原器转换表单的技术受到 Symfony Console Form 的启发。