Home > PHP Framework > ThinkPHP > body text

thinkphp multi-select delete

WBOY
Release: 2023-05-26 13:34:10
Original
645 people have browsed it

thinkphp6 is a very excellent PHP development framework. It is based on the MVC architecture. It has high development efficiency, is easy to use, is safe and reliable, and greatly simplifies the code writing process. Today, let’s talk about how to use thinkphp6 to implement multi-select deletion.

1. Introduction

Multi-select deletion is one of the common functions of modern web applications. It allows the user to select multiple items in a data table or list and then delete them. In this article, we will introduce how to use thinkphp6's controllers and models to achieve this functionality.

2. Create a database

First, we need to create a sample table in the MySQL database. We will use command line tools or phpMyAdmin to complete this step.

CREATE TABLE example_table (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL ,
email varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

This will create a new table called "example_table" with id, name and email fields.

3. Generate model and controller

Next, we need to generate a model and a controller based on the table structure created above.

Use thinkphp6's Artisan command line tool to quickly generate these files:

php think make:model ExampleModel --migration

Running the above command will generate a new model file ( app /Model/ExampleModel.php ) and a new database migration file ( database /migrations /yyyymmddhhmmss_create_example_model.php ).

php think make:controller ExampleController

Running the above command will generate a new file named ExampleController.php ( app /Controller/ExampleController.php ).

4. Write the code

Now we are ready to write the controller code to handle multi-select deletion. In the controller, we need to implement two main action functions: index (used to display all data) and delete (used to handle delete requests).

In the app/Controller/ExampleController.php file, add the following code:

<?php
namespace appcontroller;

use thinkacadeView;
use thinkRequest;
use appmodelExampleModel;

class ExampleController
{
    public function index()
    {
        $list = ExampleModel::all();

        return View::fetch('index', [
            'list' => $list,
        ]);
    }

    public function delete(Request $request)
    {
        $ids = $request->param('ids');

        foreach ($ids as $id) {
            ExampleModel::destroy($id);
        }

        return ['status' => 'success', 'message' => '删除成功'];
    }
}
Copy after login

In the above code, we first imported the class and defined two functions index and delete. The function index is used to get all the data from the ExampleModel and pass it into the template. The function delete gets the list of IDs to be deleted from the HTTP request and deletes the items using the ExampleModel::destroy method.

Next, we need to add a multi-select box and delete button to the template. Open the app /View /example /index.html file and add the following code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Example</title>
</head>
<body>
    <h1>Example</h1>
    <table>
        <thead>
            <tr>
                <th><input type="checkbox" id="check-all"></th>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($list as $item): ?>
            <tr>
                <td><input type="checkbox" name="ids[]" value="<?php echo $item->id ?>"></td>
                <td><?php echo $item->id ?></td>
                <td><?php echo $item->name ?></td>
                <td><?php echo $item->email ?></td>
            </tr>
        <?php endforeach ?>
        </tbody>
    </table>
    <button id="btn-delete">删除</button>
    <script>
        var btnDelete = document.querySelector('#btn-delete');
        btnDelete.addEventListener('click', function () {
            var ids = [];
            var checkboxes = document.querySelectorAll('input[type=checkbox][name^=ids]:checked');
            for (var i = 0; i < checkboxes.length; i++) {
                ids.push(checkboxes[i].value);
            }
            if (ids.length > 0) {
                if (confirm('确定删除?')) {
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', '/example/delete');
                    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
                    xhr.onload = function () {
                        var result = JSON.parse(xhr.responseText);
                        if (result.status == 'success') {
                            alert(result.message);
                            location.reload();
                        } else {
                            console.error(result);
                            alert('删除失败');
                        }
                    };
                    xhr.onerror = function () {
                        console.error(xhr);
                        alert('网络异常,请重试');
                    };
                    xhr.send(JSON.stringify({ids: ids}));
                }
            } else {
                alert('请选择要删除的项目');
            }
        });
        var checkAll = document.querySelector('#check-all');
        checkAll.addEventListener('click', function () {
            var checkboxes = document.querySelectorAll('input[type=checkbox][name^=ids]');
            for (var i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = checkAll.checked;
            }
        });
    </script>
</body>
</html>
Copy after login

In the above code, we used JavaScript to get all selected multi-select boxes and pass these IDs to the server's / delete route.

5. Test

Now, we can open the console and use the following command to start the web server.

php think run

Then enter localhost:8000/example in the browser to open the homepage of example, click the multi-select box to select the item to be deleted. Finally, click the Delete button to delete the selected item.

6. Conclusion

In this article, we use the controller, model and view of thinkphp6 to implement the multi-select deletion function. This feature can play an important role in web applications and optimize the user experience of the application.

The above is the detailed content of thinkphp multi-select delete. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!