Home PHP Framework ThinkPHP Implement dynamic forms using ThinkPHP6

Implement dynamic forms using ThinkPHP6

Jun 20, 2023 pm 08:49 PM
thinkphp accomplish dynamic form

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+']);
});
Copy after login
  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' => '删除失败']);
        }
    }
}
Copy after login
  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';
}
Copy after login

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>
Copy after login
  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>
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

See all articles