Home  >  Article  >  PHP Framework  >  Implement dynamic forms using ThinkPHP6

Implement dynamic forms using ThinkPHP6

WBOY
WBOYOriginal
2023-06-20 20:49:071789browse

With the popularization of the Internet and the emergence of various e-commerce platforms, dynamic forms have become an essential feature of many websites. Dynamic forms can dynamically generate pages as needed to facilitate users to fill in various information. ThinkPHP6 is an excellent PHP framework, and its powerful functions and development efficiency are widely used in the development of various web applications. This article will introduce how to use ThinkPHP6 to implement dynamic forms.

1. Preparation
First, we need to install and configure the ThinkPHP6 framework. Secondly, we need to download and install LayUI, which is a popular front-end UI framework that is very suitable for making dynamic forms.

2. Database design
Database design is a very important part. In this article we will use MySQL database for demonstration. The database structure is as follows:

CREATE TABLE form (
id int(11) NOT NULL,
form_title varchar(50) NOT NULL COMMENT 'Form title',
form_fields text NOT NULL COMMENT 'Form field',
is_active tinyint(1) NOT NULL COMMENT 'Whether it is enabled',
create_time datetime NOT NULL COMMENT 'Creation time',
update_time datetime NOT NULL COMMENT 'update time'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='dynamic form';

Among them, form_title represents the form title, form_fields Indicates form field information, is_active indicates whether it is enabled, create_time indicates creation time, and update_time indicates update time.

3. Background implementation

  1. Define routing
    First, we need to define a routing file in the route directory. Assume that the file name is form.php and the file content is as follows:
<?php
use thinkacadeRoute;

Route::group('form', function () {
    Route::rule('index', 'form/index', 'get');
    Route::rule('add', 'form/add', 'get|post');
    Route::rule('edit/:id', 'form/edit', 'get|post')->pattern(['id' => 'd+']);
    Route::rule('delete/:id', 'form/delete', 'get')->pattern(['id' => 'd+']);
});
  1. Create a controller
    Create a controller named Form.php in the app directory. The file content is as follows:
<?php
namespace appcontroller;

use appmodelFormModel;
use appalidateForm as FormValidate;
use thinkacadeView;
use thinkacadeRequest;

class Form
{
    public function index()
    {
        $formList = FormModel::paginate();
        View::assign('formList', $formList);
        
        return View::fetch();
    }
    
    public function add()
    {
        if (Request::isPost()) {
            $data = Request::param();
            $validate = new FormValidate();
            
            if (!$validate->check($data)) {
                return json(['code' => -1, 'msg' => $validate->getError()]);
            }
            
            $res = FormModel::create($data);
            
            if ($res) {
                return json(['code' => 0, 'msg' => '添加成功']);
            } else {
                return json(['code' => -1, 'msg' => '添加失败']);
            }
        }
        
        return View::fetch();
    }
    
    public function edit($id)
    {
        if (Request::isPost()) {
            $data = Request::param();
            $validate = new FormValidate();
            
            if (!$validate->check($data)) {
                return json(['code' => -1, 'msg' => $validate->getError()]);
            }
            
            $res = FormModel::update($data, ['id' => $id]);
            
            if ($res) {
                return json(['code' => 0, 'msg' => '编辑成功']);
            } else {
                return json(['code' => -1, 'msg' => '编辑失败']);
            }
        }
        
        $form = FormModel::find($id);
        View::assign('form', $form);
        
        return View::fetch();
    }
    
    public function delete($id)
    {
        $res = FormModel::destroy($id);
        
        if ($res) {
            return json(['code' => 0, 'msg' => '删除成功']);
        } else {
            return json(['code' => -1, 'msg' => '删除失败']);
        }
    }
}
  1. Create a model
    Create a model named FormModel.php in the app directory. The file content is as follows:
<?php
namespace appmodel;

use thinkModel;

class FormModel extends Model
{
    protected $table = 'form';
    protected $pk = 'id';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $dateFormat = 'Y-m-d H:i:s';
}

4. Front-end implementation

  1. Create a form editing page
    Create a file named edit.html in the view directory. The file content is as follows:
<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8">
    <title>动态表单</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/layui/css/layui.css">
</head>

<body>
    <br>
    <div class="layui-container">
        <div class="layui-row">
            <div class="layui-card">
                <div class="layui-card-header">
                    <span id="title">添加表单</span>
                </div>
                <div class="layui-card-body">
                    <form class="layui-form" method="post">
                        <input type="hidden" name="id" id="id">
                        <div class="layui-form-item">
                            <label class="layui-form-label">表单标题</label>
                            <div class="layui-input-block">
                                <input type="text" name="form_title" id="form_title" class="layui-input" lay-verify="required" autocomplete="off" placeholder="请输入表单标题">
                            </div>
                        </div>
                        <div class="layui-form-item layui-form-text">
                            <label class="layui-form-label">表单字段</label>
                            <div class="layui-input-block">
                                <textarea name="form_fields" id="form_fields" class="layui-textarea" lay-verify="required" placeholder="请输入表单字段,每个字段之间用英文逗号隔开"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit lay-filter="save">保存</button>
                                <button type="button" class="layui-btn layui-btn-primary" onclick="history.go(-1);">取消</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script src="/layui/layui.js"></script>
    <script>
        layui.use('form', function() {
            var form = layui.form;

            form.on('submit(save)', function(data) {
                $.post('/form/add', data.field, function(res) {
                    if (res.code == 0) {
                        layer.msg(res.msg, {icon: 1}, function() {
                            parent.location.reload();
                        });
                    } else {
                        layer.alert(res.msg, {icon: 2});
                    }
                });
            });
        });

        $(function() {
            var id = $.getUrlParam('id');
            if (id == undefined) {
                $('#title').text('添加表单');
            } else {
                $('#title').text('编辑表单');
                $.get('/form/edit/' + id, function(res) {
                    $('#id').val(res.id);
                    $('#form_title').val(res.form_title);
                    $('#form_fields').val(res.form_fields);
                });
            }
        });
    </script>
</body>

</html>
  1. Create a form list page
    Create a file named index in the view directory .html file, the file content is as follows:
<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8">
    <title>动态表单</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/layui/css/layui.css">
    <style type="text/css">
        .layui-table-cell {
            height: auto !important;
            white-space: normal !important;
            word-wrap: break-word;
        }
    </style>
</head>

<body>
    <br>
    <div class="layui-container">
        <div class="layui-row">
            <div class="layui-card">
                <div class="layui-card-header">
                    <a href="/form/add" class="layui-btn layui-btn-sm layui-btn-normal"><i class="layui-icon">&#xe654;</i> 添加表单</a>
                </div>
                <div class="layui-card-body">
                    <table class="layui-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>表单标题</th>
                                <th>表单字段</th>
                                <th>是否启用</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% foreach(formList as v) %}
                            <tr>
                                <td>{{ v.id }}</td>
                                <td>{{ v.form_title }}</td>
                                <td>{{ v.form_fields }}</td>
                                <td>{{ v.is_active == 1 ? "是" : "否" }}</td>
                                <td>
                                    <a href="/form/edit/{{ v.id }}" class="layui-btn layui-btn-sm layui-btn-normal">编辑</a>
                                    <a href="#" onclick="deleteItem({{ v.id }});" class="layui-btn layui-btn-sm layui-btn-danger">删除</a>
                                </td>
                            </tr>
                            {% endforeach %}
                        </tbody>
                    </table>
                    <div class="layui-pagination">
                        {{ $formList->links() }}
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="/layui/layui.js"></script>
    <script>
        layui.use('layer', function() {
            var layer = layui.layer;

            deleteItem = function(id) {
                layer.confirm('确定要删除吗?', {icon: 3}, function(index) {
                    $.get('/form/delete/' + id, function(res) {
                        if (res.code == 0) {
                            layer.msg(res.msg, {icon: 1}, function() {
                                parent.location.reload();
                            });
                        } else {
                            layer.alert(res.msg, {icon: 2});
                        }
                    });
                    layer.close(index);
                });
            };
        });

        $.getUrlParam = function(name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return unescape(r[2]);
            }
            return null;
        };
    </script>
</body>

</html>

5. Final effect
We can access the management page of the dynamic form by accessing localhost/form/index through the browser, and can add, edit and Delete a form and view a list of forms. When editing a form, users can add any number of form fields.

Figure 1: Form list page

Figure 2: Add form page

Figure 3: Edit form page

Summary
Using ThinkPHP6 and LayUI It is not difficult to implement dynamic forms. As long as we master the relevant knowledge and skills, we can easily implement this function. Of course, the code provided in this article is just an example and we can modify and optimize it as needed. I hope this article can help readers in need.

The above is the detailed content of Implement dynamic forms using ThinkPHP6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn