SSM + Layui table delete, add and modify, pagination

Keywords: Database MySQL

Delete, batch delete, add and modify SSM + Layui tables, pagination

Delete (batch delete)

This problem was encountered during the completion of the project

Get a selected row and delete it:

  1. First get the ID value in the selected Layui table
  2. The value is then passed to the back end
  3. After the Controller obtains the value, execute the corresponding Service method...

Some HTML codes are as follows:
Table section:

<table id="order" class="layui-hide" lay-filter="order">
</table>

Script part:

//The order in the next line corresponds to the value of the layer filter
        table.on('toolbar(order)', function (obj) {
            let $ = layui.$;
            //Get which of the multiple selection boxes are selected
            let checkStatus = table.checkStatus(obj.config.id);
            //Get selected data
            let data = checkStatus.data;
            let datas = [];
            for (let i = 0; i < data.length; i++) {
                // Put the selected ID value into the array
                datas.push(data[i].orderId);
            }
            switch (obj.event) {
                case 'add':
                    console.log("add");
                    break;
                case 'update':
                    console.log("update");
                    break;
                case 'delete':
                    if (checkStatus.data.length === 0) {
                        layer.msg("Please select a row")
                    } else {
                        layer.confirm('OK to delete?', {icon: 3, title: 'warning'}, function (index) {
                            console.log(data[0].orderId);
                            //Get the selected Id value and assign it to data.id
                            data.id=data[0].orderId;

                            $.ajax({
                                url: '/orders/deleteOrders',
                                type: 'POST',
                                data: {id: data.id},
                                success: function (data) {
                                    console.log('Delete succeeded');
                                    table.reload('order');
                                },
                                error: function () {
                                    console.log("ajax error");
                                }
                            })
                            layer.close(index);
                        });
                    }
                    break;
            }
        })

Note that although this sentence in IDEA is wrong:

However, the ID value of the selected row can still be obtained correctly

Backend Controller code:

    @RequestMapping("/deleteOrders")
    @ResponseBody
    public String deleteOrder(@RequestParam(name = "id") String orderId, Model model){
        System.out.println(orderId);
        orderService.deleteOrderByOrderId(orderId);
        return "order/ordersMain";
    }

The principle of selecting multiple batch deletion is the same. Before the meeting, it's not difficult
Just pass all IDs of multiple values to the backend, and the backend will delete all IDs

increase

The principle of adding is the same. You only need to write one more and a form interface will pop up.
The approximate operation is as follows:

<div style="margin: 5%; display: none" id="window" class="layui-form">
    <form class="layui-form" action="" lay-filter="newOrder" id="newOrder">
    //Content omitted
    </form>
</div>

Pop up a new window: the form written in the front

	layer.open({
		type: 1,
		title: 'Add new order',
		area: ['500px', '500px'],
		btn: ['determine', 'cancel'],
		// Here corresponds to the id of the previous div
		content: $('#window'),
		yes: function () {
		}
	})

Form validation method 1

For the add operation, it should be noted that the primary key is duplicate (the primary key cannot be empty), and items with the same ID cannot be added:
success: function (data)
The value of data returned from the back end is used to determine whether there is duplication, and the back end is used to specifically implement whether there is duplication (database query statement). This is my method. There is another method that uses form validation, which is introduced in the form validation area later

$.ajax({
                url: '/orders/addOrders',
                type: 'POST',
                data: {newOrderInfos: newOrderInfos},
                success: function (data) {
                    if (data === 'success') {
                        console.log('Successfully added');
                        console.log(data);
                        table.reload('order');
                    } else if (data === 'duplicate') {
                        layer.msg('This order already exists!')
                    } else {
                        console.log('Add failed');
                        table.reload('order');
                    }
                },
                error: function () {
                    console.log("ajax error");
                }
            })

A new BUG appears in the add order. It prompts me that the primary key is duplicate. However, both the page and the database have been added successfully, but the error is still reported. However, I can only use the on duplicate key update statement. For details, see: MySQL INSERT statement, if the primary key is duplicate, update

Form submitted twice

  1. Note that return false is required at the end of form submission, otherwise it will be submitted twice
  2. Quote twice layui.js , the form will also be submitted twice

paging

When more content is added, the table needs to be paginated:

Add by document page:true It's not over
Read the document:

The front end will pass two parameters, as shown in the figure above
The backend should query based on these two variables, otherwise all the results will be displayed.
It's equivalent to that the frame just helps you to switch the numbers between page numbers, while the real content change needs to be realized by yourself

The Controller code is as follows: (layuiResult is a user-defined class, which is convenient to return values and has no relationship with paging)
Two parameters are passed in to get the order list, which are equivalent to the range

    public layuiResult<Order> check(HttpServletRequest request) {
        // Paging operation to obtain the data from the front end
        int page = Integer.parseInt(request.getParameter("page"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        System.out.println(page +"     "+ limit);

        layuiResult<Order> layuiResult = new layuiResult<>();
        // Orders displayed in pages
        List<Order> orderList = orderService.getOrderList((page-1)*limit,limit);
        // Get all orders in order to count the number
        List<Order> allOrderList = orderService.getAllOrderList();
        // Custom class convenient return value
        layuiResult.setData(orderList);
        layuiResult.setCount(allOrderList.size());
        return layuiResult;
    }

Mapper layer code:
from is the start position, to is the end position. In this way, you can customize the query, pass the results of each page to the front end, and realize paging operation

    <select id="getOrderList" resultType="Order">
        select
            orderid as orderId,
            userid as userId,
            orderdate as orderDate,
            sendprovince as sendProvince,
            sendcity as sendCity,
            senddetailed as sendDetailed,
            receiveprovince as receiveProvince,
            receivecity as receiveCity,
            receivedetailed as receiveDetailed
        from ordersinfo
        limit #{from},#{to}
    </select>

Service layer code:

    @Autowired
    private OrderMapper orderMapper;

    public List<Order> getOrderList(int from, int to){
        return orderMapper.getOrderList(from, to);
    }

Form validation (using form.verify Combined with ajax)

Then, when adding elements before, the primary key is repeated (the primary key cannot be empty), and items with the same ID cannot be added to verify the form.

Solution: Using form.verify Combined with ajax for judgment, this method becomes to be verified after submission, which has not been solved yet

The backend Mapper and Service query the database to see if there are duplicates. This code is relatively simple and will not be introduced here.

Front end code:
Pay attention to add this sentence async:false ,

        // Form Validation 
        form.verify({
        // orderNumber corresponds to lay verify = "orderNumber"
            orderNumber: function (value) {
                let $ = layui.$;
                let msg = '';
                if (value==="")
                    msg='Order cannot be empty !'
                $.ajax({
                    url: '/orders/isDuplicate',
                    type: 'POST',
                    data: {id: value},
                    // Pay attention to this sentence
                    async:false,
                    success: function (result) {
                        if (!result){
                            msg = "This order already exists!";
                        }
                    }
                })
                // Note that the return statement is written here
                return msg;
            },
        })
<input name="orderNumber" id="orderNumber" lay-verify="orderNumber" autocomplete="off"
                               class="layui-input">

Controller code:
Call service to determine whether the order exists

    @RequestMapping("/isDuplicate")
    @ResponseBody
    public boolean isDuplicate(@RequestParam(name = "id") String orderId){
        System.out.println(orderId);
        Order order = orderService.findOrder(orderId);
        return order == null;
    }

Modify and edit

Editing is essentially the same as adding. The only difference is that when the editing layer pops up, the table in it must have the information of the selected row

The main codes assigned to the table in advance are as follows:‘

Note: in form.val('filter', object) statement

  1. Filter is the value of the layer filter in the table
  2. The key value in the second parameter is the name and value corresponding to the form element.
            //Get which of the multiple selection boxes are selected
            let checkStatus = table.checkStatus(obj.config.id);
            //Get selected data
            let data = checkStatus.data;

// Some codes are omitted, only the codes related to assignment are shown
                case 'update':
                    if (checkStatus.data.length === 0) {
                        layer.msg("Please select a row")
                    } else if (checkStatus.data.length > 1) {
                        layer.msg("Only one order can be edited at the same time")
                    } else {
                        console.log(data[0].orderId)
                        form.val('updateForm', {
                            'orderNumber': data[0].orderId,
                            'userNumber': data[0].userId,
                            'date': data[0].orderDate,
                            'sendProvince': data[0].sendProvince,
                            'sendCity': data[0].sendCity,
                            'sendDetailed': data[0].sendDetailed,
                            'receiveProvince': data[0].receiveProvince,
                            'receiveCity': data[0].receiveCity,
                            'receiveDetailed': data[0].receiveDetailed,
                            'updateStatus': data[0].status === "yes" ? 'yes' : 'no',
                        })
                        layer.open({
                            type: 1,
                            title: 'Add new order',
                            area: ['500px', '500px'],
                            content: $('#updateWindow'),
                            yes: function (index) {
                            }
                        })
                    }
                    break;

When assigning a value to a radio box, you can use a ternary expression

The operation principle of the back-end code is the same as the new one before, which will not be stated here

summary

Problems to be solved:

  1. Table search function
  2. Table sorting can only be current page sorting, not all sorting

Due to the large number of source code, it is inconvenient to display here, and there are people who need to communicate with each other.

Posted by newhen on Sun, 21 Jun 2020 18:47:53 -0700