select2 ajax dynamically fetches data and echoes it

There is a requirement: to assign roles to an employee, you must first obtain the roles that the employee already has, and obtain a list of all roles.

The specific effects are as follows

Implementation steps:

1. Load all roles list

Because it's a static pop-up box, you can't send a request to load the role list every time you open the static box, and then the page initialization should be completed.

 /**
         * Page initialization
         */
        $(function () {
            initRolesSelect();
        }
        
         function initRolesSelect() {
            Ctool.ajax.post({
                url: '/admin/sys/role/list',
                success: function (res) {
                    $('#selectRole').select2({
                        theme: "bootstrap",
                        multiple: true, //Open multiple selection
                        data: res.data,  //Data returned
                        minimumResultsForSearch: -1 //No search
                      
                    });

                }
            })
        }

According to the official document, as long as the format returned is

{ "results": [ { "id": 1, "text": "Option 1" }, { "id": 2, "text": "Option 2", "selected": true }, { "id": 3, "text": "Option 3", "disabled": true } ] }

select2 in this format is automatically rendered. Selected indicates whether it is selected when loading, and disabled indicates that it cannot be edited. Of course, you can also customize the template. Because the list of roles needs to be loaded at page initialization time, the roles already owned by the employee cannot be returned. The defined return format is:

console.log(res.data) //Data returned by back end

(4) [{...}, {...}, {...}, {...}]
0: {id: 1, text: "system administrator"}
1: {id: 4, text: "staff"}
2: {id: 5, text: "Boss"}
3: {id: 7, text: "Code farming"}
length: 4

2. Find the role already owned by the personnel id and echo it

//Echo data 
function echoSelect2(dom,value){
    $.each(value,function(index,value){
        $(dom).append(new Option(value.name, value.id, false, true));
    });
    $(dom).trigger("change");
}

//Original: https://blog.csdn.net/u011067966/article/details/79154391 

In this way, a new option will be created for echo, but there will be more options in the drop-down list.

 

Finally, check the official documents: $('ාselectrole'). Val (['1 ','2']); $('ාselectrole'). Trigger ('change '); echo can be realized through the change event monitoring in the following table of the incoming array.

             /**
         * Assign role echo
         * @param id
         */
        function allotRoleBtn(id) {
            $('#selectRole').val(null).trigger('change'); / / clear the static box before loading.
            if (id) {
                Ctool.ajax.post({
                    url: '/admin/sys/user/allotsearch',
                    data: {id: id},
                    success: function (res) {
                        $('#allotRoleModal').modal('show'); / / open the static box
                        $('#allotRoleFrom').setForm(res.data.user); / / echo user name and nickname

                        var role = res.data.role;//Get the role owned by the employee
                        var roles = []; //Define an empty array to hold the role id

                        if (role != "") {
                            $.each(role, function (index, role) {
                              
                               roles.push(role.id);

                            });
                            $('#selectRole').val(roles);
                            $('#selectRole').trigger("change");


                        }


                    }


                });
            }
        }

 

Posted on Tue, 03 Dec 2019 18:08:00 -0500 by s1yman