使用JSON构建动态HTML表单,Artificer可以做到这一点。

dev-master 2017-04-18 11:13 UTC

This package is not auto-updated.

Last update: 2024-09-20 19:30:07 UTC


README

使用JSON构建动态HTML表单,Artificer可以做到这一点。它位于Laravel Collective Html之上。

简介

Artificer提供了一个简单的API,通过将模式存储在JSON中,生成HTML表单。它为后续请求缓存生成的HTML表单,提高了表单生成和提供速度。

先决条件

  1. 需要 php >= 7.1
  2. 需要 laravel/framework >= 5.4
  3. 需要 laravelcollective/html >= 5.4

安装

要通过composer安装此包,请在终端运行以下命令

composer require santhoshkorukonda/artificer

配置

在开始使用之前,我们需要进行一些配置。

将我们的新提供者 ArtificerServiceProvider 添加到 config/app.php 文件中的 providers 数组

<?php

return [
    'providers' => [
        SantoshKorukonda\Artificer\ArtificerServiceProvider::class,
    ],
];

接下来,将别名添加到 config/app.php 文件中的 aliases 数组

<?php

return [
    'aliases' => [
        SantoshKorukonda\Artificer\ArtificerFacade::class,
    ],
];

接下来,通过在 config/cache.php 文件中的 stores 数组中添加配置来为 Artificer 创建一个缓存存储

<?php

return [
    'stores' => [
        'artificer' => [
            'driver' => 'file',
            'path' => storage_path('artificer/cache'),
        ]
    ],
];

接下来,通过在 config/filesystems.php 文件中的 disks 数组中添加配置来为 Artificer 创建一个文件系统磁盘

<?php

return [
    'disks' => [
        'artificer' => [
            'driver' => 'local',
            'root' => storage_path('artificer/views'),
        ],
    ],
];

生成表单

一个带有控制器和示例json文本的表单生成代码示例。

<?php

namespace App\Http\Controllers;

use Artificer;

class FormController extends Controller
{
    /**
     * Build a sample form from the json.
     *
     * @return html
     */
    public function create()
    {
        // Here json is hardcoded as string to explain you how it works,
        // it can even fetched form a database or a remote http call etc.
        // So whatever it might just fetch the string, decode it and send
        // the schema to build the form.
        $schema = json_decode($this->getJson());
        $data = Artificer::build($schema);
        return view("welcome")->with($data);
    }

    /**
     * Define a sample json schema for form generation.
     *
     * @return string
     */
    protected function getJson()
    {
        return '{}';
    }
}

生成表单非常简单。

理解表单JSON模式

查看以下文档,了解如何构建Artificer可识别的json模式。

表单模式

表单模式属性与 laravelcollective 的表单选项相同。

{
    // define attributes for the form with the key "attributes" in json schema.
    "attributes": {
        "route": "route.name",
        "method": "POST",
        "files": true,
        "id": "Enquiry",
        "class": "form"
    },
    "components": {
        ...
    }
}