[Ztree] Perfectly implements the check box function, and ztree implements the check box function.

Source: Internet
Author: User

[Ztree] Perfectly implements the check box function, and ztree implements the check box function.

In the permission system, most pages use a tree structure. The most commonly used is the loading and clicking events of tree resources. In addition, ztree can implement many functions. Let's take the addition of check boxes as an example. Let's take a deeper look at the application of ztree.

I. instance description

In the user management module, you need to add roles to users, and there is a many-to-many relationship between users and roles. Here, we can load two role tree resources and exchange data between the two trees to obtain the role resources owned by the user. The effect is as follows:

1. User Information Portal

2. Load role information

The "Assign" button in the Datagrid table is used to assign roles to a single user, while the "batch assign roles" button under the search box is used to assign roles to multiple users, the two are combined in the implementation process.

1) if you select a user, the "assigned role" in the role tree on the right is the role that the user already has, in the left-side role Tree "allocable roles", all roles except the roles owned by this user are displayed.

2) if multiple users are selected, the right-side role tree is empty, and the left-side role tree is all roles.

3. Added and removed Functions

The specific functions are implemented by several buttons. The buttons "add, add, remove, and remove" are used to manage data transmission between the two role trees, without interaction with the background; the "OK" button is used to save the page operation results to the database. The "reset" button restores the role assignment window to the initialization status.

After "OK", the corresponding user role information is saved in the database.

II. Specific implementation

1. In HTML, design a Windows window to hold two role trees.

<Div id = "groupDistributeRole" class = "easyui-window" title = "batch assignment role" style = "width: 700px; height: 500px; padding: 0px; "data-options =" collapsible: false, minimizable: false, maximizable: false, modal: true "> <div class =" easyui-layout "style =" width: 630px; height: 370px; margin-top: 20px; margin-left: 20px; margin-right: 20px "> @ * 1. left: All roles * @ <div data-options = "region: 'west', title: 'allocatable role ', accordion: 'false'" style = "width: 260px; "> <ul id =" roleTree "class =" ztree "> </ul> </div> @ * 2.: Add Remove button * @ <div id = "RoleButton" data-options = "region: 'center'" style = "width: 100px; border: 0px; font-size: 26px; text-align: center; margin-top: 60px "> <a href =" javascript: void (0) "class =" easyui-linkbutton "onclick =" addRole () "> Tian Jia> </a> <a href =" javascript: void (0) "class =" easyui-linkbutton "onclick =" addRoleAll () "> Add all> </a> <a href =" javascript: void (0) "class =" easyui-linkbutton "onclick =" removeAddedRoleTree () "> <remove </a> <a href =" javascript: void (0) "class =" easyui-linkbutton "onclick =" removeAllAddedRole () "> <remove all </a> </div> @ * 3. right: assigned role * @ <div data-options = "region: 'east', title: 'assigned role '" style = "width: 260px; "> <ul id =" addedRoleTree "class =" ztree "> </ul> </div> <div class =" easyui-panel "style =" width: 686px; margin-top: 20px; border: 0px; "> <div style =" height: 50px; font-size: 26px; text-align: center; "> <a href =" javascript: void (0) "class =" easyui-linkbutton "data-options =" iconCls: 'icon-OK '"onclick =" RoleOk () "> OK </a> <a href =" javascript: void (0) "class =" easyui-linkbutton "data-options =" iconCls: 'icon-undo '@ *, plain: true * @ "onclick =" RoleReset () "> Reset </a> </div>
2. JavaScript

1) first obtain the information in the Datagrid table and determine whether the selected data is a single user or multiple users, so as to load the corresponding role tree resources.

Var rowData; function groupDistributeRole () {// obtain the selected data rowData =$ (dg_student ). datagrid ("getSelections"); // if no row is selected, the message if (rowData. length = 0) {$. messager. alert ("prompt message", "select the user to assign a role! ", 'Info'); return;} // open the role allocation window $ ('# groupDistributeRole '). window ('open') addedRoleTree. pFunction. loadTree (); // load the role tree roleTree. pFunction. loadTree ();}

2) Load Code of two role trees

Var roleTree = {/*** all initialization operations */pFunction: {zTree: '', setting: {view: {showLine: false, // do not display the connection line showIcon: false // do not show icon}, check: {enable: true // show check box}, data: {key: {name: "RoleName"}, simpleData: {enable: true, idKey: "RoleId", rootPId: "0" }}, // load resource loadTree: function () {if (rowData. length = 1) {$. post ("/UserManage/queryroleappstaddedrole", {userId: rowData [0]. userId}, function (roleInfo) {$. fn. zTree. init ($ ("# roleTree"), roleTree. pFunction. setting, roleInfo);} else {$. post ("/UserManage/QueryAllRole", null, function (roleInfo) {$. fn. zTree. init ($ ("# roleTree"), roleTree. pFunction. setting, roleInfo) ;}}}; var addedRoleTree ={/ *** all initialization operations */pFunction: {zTree: '', setting: {view: {showLine: false, // do not show connection lines showIcon: false // do not show icons}, check: {enable: true // show check boxes}, data: {key: {name: "RoleName",}, simpleData: {enable: true, idKey: "RoleId", rootPId: "0" }}}, // load resource loadTree: function () {if (rowData. length = 1) {$. post ('/UserManage/queryrolebyuserid', {userId: rowData [0]. userId}, function (roleInfo) {$. fn. zTree. init ($ ("# addedRoleTree"), addedRoleTree. pFunction. setting, roleInfo);} else {$. fn. zTree. init ($ ("# addedRoleTree"), addedRoleTree. pFunction. setting); // load an empty tree }}}};
3) several buttons used to operate two role trees

// Cancel the operation function RoleReset () {// reload the tree addedRoleTree. pFunction. loadTree (); roleTree. pFunction. loadTree ();} // Add role function addRole () {// obtain the tree of the added node -- addedRoleTree addedRoleObject = $. fn. zTree. getZTreeObj ("addedRoleTree"); roleObject = $. fn. zTree. getZTreeObj ("roleTree"); // nodes is an array (json) array and is the var nodes = roleObject of all selected nodes. getCheckedNodes (true); // Add the selected node to the assigned role -- addedRoleTree addedRoleObject. addNodes (null, nodes); // Delete the node in the unassigned role -- roleTree for (var l = nodes. length, I = l-1; I> = 0; I --) {roleObject. removeNode (nodes [I]) ;}// add all role functions addRoleAll () {// retrieve the tree of the added node -- addedRoleTree addedRoleObject = $. fn. zTree. getZTreeObj ("addedRoleTree"); roleObject = $. fn. zTree. getZTreeObj ("roleTree"); // obtain information about all nodes -- roleTree var nodes = roleObject. getNodes (); // nodes is an array (json) array. It is an array of all selected nodes. // Add the selected nodes to the assigned role-addedRoleTree addedRoleObject. addNodes (null, nodes); // delete all nodes in the unassigned role -- roleTree (the deletion of I -- is valid, and the deletion of I ++ will cause an error) for (var l = nodes. length, I = L-1; I> = 0; I --) {roleObject. removeNode (nodes [I]) ;}// Delete the role function removeAddedRoleTree () {// retrieve the tree of the added node -- addedRoleTree addedRoleObject =$. fn. zTree. getZTreeObj ("addedRoleTree"); roleObject = $. fn. zTree. getZTreeObj ("roleTree"); // obtain the information of the selected node -- addedRoleTree var nodes = addedRoleObject. getCheckedNodes (true); // nodes is an array (json), which is an array of all selected nodes. // Add the selected nodes to an allocable role -- RoleTree roleObject. addNodes (null, nodes); // Delete the node in the assigned role -- addedRoleTree for (var l = nodes. length, I = l-1; I> = 0; I --) {addedRoleObject. removeNode (nodes [I]) ;}// delete all role functions removeAllAddedRole () {// retrieve the tree of the added node -- addedRoleTree addedRoleObject =$. fn. zTree. getZTreeObj ("addedRoleTree"); roleObject = $. fn. zTree. getZTreeObj ("roleTree"); // obtain the node information of all assigned role trees -- addedRoleTree var nodes = addedRoleObject. getNodes (); // nodes is an array (json) array, which is the information of all selected nodes // assigned roles, add to the allocable role -- RoleTree roleObject. addNodes (null, nodes); // Delete the information in the assigned role -- addedRoleTree for (var l = nodes. length, I = l-1; I> = 0; I --) {addedRoleObject. removeNode (nodes [I]);}
4) Save the page operation results to the database

// Save operation function RoleOk () {// obtain the tree of the added node -- addedRoleTree addedRoleObject = $. fn. zTree. getZTreeObj ("addedRoleTree"); var nodes = addedRoleObject. getNodes (); // put the node's RoleId in an Array var roleArray = new Array; for (var I = 0; I <nodes. length; I ++) {var obj = new Object; obj. roleId = nodes [I]. roleId; roleArray. push (obj) ;}$. post ('/UserManage/adduserrole', {userData: JSON. stringify (rowData), roleData: JSON . Stringify (roleArray)}, function (savaInfo) {// close the role assignment window $ ('# groupDistributeRole'). window ('close'); alert ("saved successfully! ");});}
3. In Controller, it is a simple call process for the methods used in js.

# Region searches for all roles that the user does not have according to the user ID. Wang jingna, August 25, 2015 public ActionResult queryrolepolictaddedrole () {var UserId = Request. form ["userId"]; Guid userId = new Guid (UserId); List <RoleViewModel> listRole = iUserManageService. queryroleinclutaddedrole (userId); var listTreeRole = listRole. select (n => new {n. roleId, n. roleName }). toList (); return Json (listTreeRole, JsonRequestBehavior. allowGet) ;}# endregion # region AddUserRole () Add User Role Wang jingna August 27, 2015 public void AddUserRole () {// convert user information var UserData = Request ["userData"]; javaScriptSerializer jsUser = new JavaScriptSerializer (); List <UserViewModel> listUser = jsUser. deserialize <List <UserViewModel> (UserData); // convert the role information var RoleData = Request ["roleData"]; JavaScriptSerializer jsRole = new JavaScriptSerializer (); list <RoleViewModel> listRole = jsRole. deserialize <List <RoleViewModel> (RoleData); // call the server's add method iUserManageService. addUserRole (listUser, listRole);} # endregion
Iii. Summary

The learning of ztree is mainly based on documents. However, in the implementation process, we still encounter various small problems. With the emergence and solution of these problems, we have gained a deeper understanding of it. The following knowledge points are mainly used to implement the ztree check box function:

1. If the tree structure is not displayed, all data is displayed as one column. Generally, idKey and pIdKey must be set for tree structure. Here, you only need to set idKey or let idKey = pIdKey.

simpleData:                {                    enable: true,                    idKey: "RoleId",                    rootPId: "0"                }

2. Two check boxes

To implement the check box function of ztree, you must first add the check box, that is, setting. check. enable = true. However, after adding this function, two check boxes are displayed.


This is because the check box is repeatedly loaded. Here, it is because a js is introduced.

3. The returned result of the node acquisition operation on the tree is a json string, which is an array (json) array and can be operated as an array.

// Put the node's RoleId in an Array var roleArray = new Array; for (var I = 0; I <nodes. length; I ++) {var obj = new Object; obj. roleId = nodes [I]. roleId; roleArray. push (obj );}

4. tree node deletion. nodes is the node to be deleted. to delete a node, use I -- operation. I ++ operation will change the node length, thus, the node to be deleted cannot be found or some nodes are missing.

// Delete the node selected from the unassigned role -- roleTreefor (var l = nodes. length, I = l-1; I> = 0; I --) {roleObject. removeNode (nodes [I]);}
Summary:

Learning is a step-by-step process. Continuous attempts can lead to more problems. Learning Through these problems not only gives us more understanding, you can also exercise the ability to solve problems. One day, these problems will become fewer and more quality-oriented.



Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.