ExtJs tree control entry --- TreePanel

This article will give you a detailed explanation of the use ExtJs tree control, if any deficiencies, please correct me, my QQ: 1113905744,
all of the code used in the article will attach the end of the article!

There are two renderings

With check boxes and check boxes without trees, there is explained hereinafter, mindful of.
Note: The original data contains check boxes are checked attribute, no attribute is not checked checkbox

  1. Without box
    Hello there!  This is the first time you use ** ** Markdown editor exhibited welcome page.  If you want to learn how to use Markdown editor, I can read this article carefully, understand the basic grammar of Markdown.
  2. With check boxes
    Here Insert Picture Description

Invocation:

Here Insert Picture Description

Detailed:

  1. Creating a base class that is packaged ExtJs class, which contains: Click select all child nodes parent node, checkbox echo method and the like . Directly used on the line:
    Here Insert Picture Description
  2. Create a tree control: 1. class name when more than one step to create a base class name shall prevail 2. Data Sources (explained next)
    Here Insert Picture Description
  3. The key to creating a data source, the tree control. Data coming back from the tree, I will explain in detail in several steps, the first renderings:
    Here Insert Picture Description
    Then as we explain in detail how the data is organized into a background data nested in the form of pictures as follows:
  • Field finishing the tree structure: dept_code every three representatives of a tree, six second-level tree, in ascending order
    Here Insert Picture Description
  • Organize data follows the code I would put the end of the article.
    Here Insert Picture Description
  • The data found to insert two attributes: Leaf, the checked ; nested coding: the coding is defined in the database and your level three. The following method only need to modify those two places I marked in the figure on itHere Insert Picture Description Here Insert Picture Description

Code:

Front Code:

Base class:

Ext.define('Ext.ux.tree.CustomeTreePanel', {
	extend : 'Ext.tree.Panel',
	rootVisible : false,
	useArrows : true, //箭头样式
	frame : false, //圆角
	header : false,
	indeterminateCls : 'x-tree-checkbox-indeterminate',
	width : 350,
	height : 200,
	initComponent:function(){
		var me = this;
		me.callParent();
	},
	listeners : {
		checkchange : function(node, checked) {
			var me = this;
			me.setChildrenCheckedStatus(node, checked);
			me.updateParentCheckedStatus(node, checked);
		},
		collapse:function(p){

		}
	},

	setChildrenCheckedStatus : function(node, check) { 
		var me = this;
		var len = node.childNodes.length;
		if (len <= 0 || node.get('disabled') === true) {
			if (node.get('disabled') === false)
				node.set('checked', check);
			return node.get('checked') ? 1 : -1;
		} else {
			var sumcount = 0;
			for (var index = 0; index < len; index++) {
				var subnode = node.childNodes[index];

				subnode.set('checked', check)

				sumcount = sumcount+ me.setChildrenCheckedStatus(subnode, check);
			}
			if (len === Math.abs(sumcount)) {
				me.unsetThirdState(node);
				node.set('checked', check);
				return node.get('checked') ? 1 : -1;
			} else {
				me.setThirdState(node);
				return 0;
			}

		}
	},

	updateParentCheckedStatus : function(node, check) {
		var me = this;
		var nodeparent = node.parentNode;
		if (!nodeparent) {
			return;
		} else {
			var len = nodeparent.childNodes.length;
			var sumcount = 0;
			for (var index = 0; index < len; index++) {
				var subnode = nodeparent.childNodes[index];
				if (me.isThirdState(subnode)) {
					sumcount = sumcount + 0;
				} else {
					if (subnode.get('checked')) {
						sumcount = sumcount + 1;
					} else {
						sumcount = sumcount - 1;
					}
				}
			}
			if (len === Math.abs(sumcount)) {
				me.unsetThirdState(nodeparent);
				nodeparent.set('checked', check);
			} else {
				me.setThirdState(nodeparent);
			}
			me.updateParentCheckedStatus(nodeparent, check);
		}
	},

	isThirdState : function(node) {
		return node.get('cls') == this.indeterminateCls;

	},

	setThirdState : function(node) {
		node.set('cls', this.indeterminateCls);
		node.set('checked', true);
	},

	unsetThirdState : function(node) {
		node.set('cls', '');
	},

	getLeafIdSelections : function() {
		var me = this;

		try {
			var tree_selections = me.getView().getChecked(), result = []; 
			
			Ext.Array.each(tree_selections, function(rec) {
				console.log(rec); 
				if (rec.get('text')!="Root") {
					result.push(rec.get('id')/* ,rec.get('text') */);
				}
			});

			return result;
		} catch (e) {
			debug('[error in accessPanel getSelections]');
			debug(e);
		}
	},

	setSelections : function(codes) {
		var ids = codes.split(",");
		var me = this;
		if (ids[0] && ids[0]['id']) {
			ids = Ext.Array.pluck(ids, 'id');
		}

		me.getRootNode().cascadeBy(
				function() {
					var currNode = this;
					if (currNode.get('leaf')) {
						currNode.set('checked',
								ids.indexOf(currNode.get('id')) > -1);
						me.updateParentCheckedStatus(currNode, ids
								.indexOf(currNode.get('id')) > -1);
					}
				});
	},

	
});

The tree control:

bankSysEditTreePanel = Ext.create('Ext.ux.tree.CustomeTreePanel',{
	title : "机构列表",  //树控件名称
	expanded:true, //默认展开树节点  没效果 需要优化一下
	rootVisible:false,  //是否显示root节点
	scrollable: 'y',   //滚动条
	animScroll:true,//动画效果
	store:	userBankTreeStore,      //调用的数据源
	width : '100%',
	height : '100%',
	border : true,
	animCollapse : true,
	animate : true,
	listeners:{  //监听器
	
	}
});   

data source

var userBankTreeStore;
userBankTreeStore = Ext.create('Ext.data.TreeStore', {
   fields: ["bank_name", "bank_id"],    //Model
        autoLoad : true,
        pageSize : 15,
        sorters : {      //排序
            property : 'bank_name',
            direction : 'ASC'
        },  
	clearOnLoad : true,
	defaultRootId : '-1',
	proxy : {
		type : 'ajax',
		url : getServerHttp() +"/nh-bank/cp/bank/bankList" ,     //后台接口路径
		reader:{
			type:'json',
		},
	},
	root:{
		expanded:true,
	},
	autoLoad:false
});

Background Code:

Interface method:

 @ApiOperation(value = "树形机构")
	  @GetMapping("/bankListTo") 
	  public JSONArray bankListTo() { 
		  List<Map<String,Object>> banklist = bankService.allbank();  //查询要整理的原始数据
		  JSONArray result = JSONArray.parseArray(TreeTools.turnListToTree_bankAdd(banklist));  //整理为嵌套形式
		  return result; 
	  }

The leaf, checked attribute data into the original method:

 public static List<Map<String, Object>> handleTree_bank(List<Map<String, Object>> menuList, boolean isChecked) {
	  for (Map<String, Object> map : menuList) {
	   map.put("id", map.get("dept_code"));
	   map.put("iconCls", map.get("url"));
	   map.put("text", map.get("bank_name"));
	   map.put("leaf", true);
	   if (isChecked) {
	    map.put("checked", false);
	   }
	  }

The data is organized into a tree structure:

@SuppressWarnings("unchecked")
	public static String turnListToTree_bank(List<Map<String, Object>> menuList, boolean isChecked) {
		// TODO 转换List为树形结构
		menuList = handleTree_bank(menuList, isChecked);

		List<Map<String, Object>> nodeList = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> node1 : menuList) {
			String node1_code = (String) node1.get("dept_code");
			String node1_parent_code = node1_code.substring(0, node1_code.length() - 3);

			boolean mark = false;
			for (Map<String, Object> node2 : menuList) {
				String node2_code = (String) node2.get("dept_code");

				if (node1_parent_code != null && node1_parent_code.equals(node2_code)) {
					mark = true;
					if (node2.get("children") == null) {
						node2.put("children", new ArrayList<Map<String, Object>>());
					}
					((List<Map<String, Object>>) node2.get("children")).add(node1);
					node2.put("leaf", false);
					if (!isChecked) {
						node2.put("expanded", true);
					}
					break;
				}
			}
			if (!mark) {
				nodeList.add(node1);
			}
		}
		return JsonUtil.toJson(nodeList);
	}

Attach stepped on some of the work in the pit:

  1. Save tree node: Method redlining base class can be found in the above, the call (name tree control method name.)
    Here Insert Picture Description
    2. echo tree node: means for data echoed string comma-separated, i.e. the for paper finishing nested coding tree structure

Here Insert Picture Description
Here Insert Picture Description
code show as below:

function myEdit(kid) {
	var  me =  this;
	Ext.Ajax.request({
		url : getServerHttp() +"/nh-bank/cp/roleAuth/edit_form?kid=" + kid,
		success : function(response) {
			var json = Ext.JSON.decode(response.responseText);
			if(json){
				me.showEditPanel(json.result);
			}
			// 列表树回显数据
			window.EditTreePanel.setSelections(json.result.roleAuths);  //括号中的数据为逗号分隔的字符串
		},
		failure : function(response) {
			Ext.Msg.alert("提示", "操作失败!");
		}
	});
}// #myEdit

Published 13 original articles · won praise 8 · views 1313

Guess you like

Origin blog.csdn.net/yaoliyuan0922/article/details/100127391