1. 程式人生 > >TP5.1 Layui (無限級)樹形表格treetable

TP5.1 Layui (無限級)樹形表格treetable

例子: TP5.1 + Layui 2.4.0

一、模板程式碼:

<!DOCTYPE html>
<html>				
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>導航選單</title>
	<link rel="stylesheet" href="__STATIC__/layui/css/layui.css" media="all">
	<script src="__STATIC__/layui/layui.js"></script> 
	<link rel="stylesheet" href="__ADMIN__/css/index.css" media="all">
</head>
<body style="background-color: #FFFFFF;">
<!-- 你的HTML程式碼 -->
<!-- 表格 -->
<div class="layui-fluid">

<div style="margin-top: 20px;">
	     <div class="layui-btn-group">
					  <button class="layui-btn " id="btn-expand"><i class="layui-icon layui-icon-down"></i> 全部展開</button>
					  <button class="layui-btn " id="btn-fold"><i class="layui-icon layui-icon-left"></i> 全部摺疊</button>
					  <button class="layui-btn " id="btn-refresh"><i class="layui-icon layui-icon-loading"></i> 重新整理表格</button>
			  </div>
        <div class="layui-inline">
        	<input class="layui-input" id="edt-search" value="" placeholder="輸入關鍵字">
        </div>
      
        <button class="layui-btn" id="btn-search"  type="button">搜尋</button>
</div>


<!-- 操作列 -->
<table id="table1" class="layui-table" lay-filter="table1"></table>
<script type="text/html" id="toolbarDemo">
    <!--<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a>-->
    
<div class="layui-btn-group">
  <button class="layui-btn layui-btn-primary layui-btn-xs" lay-event="add"><i class="layui-icon layui-icon-add-1"></i> 增加</button>
  <button class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i> 編輯</button>
  <button class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i> 刪除</button>
</div>
</script>
<script type="text/html" id="auth-state">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a>
</script>
<!-- 表格end -->
<script>
    layui.config({
        base: '__STATIC__/menu/'
    }).extend({
        treetable: 'treetable-lay/treetable'
    }).use(['layer', 'table', 'treetable','form','jquery'], function () {
        var $ = layui.jquery;
        var table = layui.table;
        var form = layui.form;
       // var element = layui.element;
        var layer = layui.layer;
        var treetable = layui.treetable;

        // 渲染表格
        var renderTable = function () {
            layer.load(2);
            treetable.render({
                treeColIndex: 1,
                treeSpid: -1,
		            treeIdName: 'id',
		            treePidName: 'pid',
                treeDefaultClose: true,
                treeLinkage: false,
                elem: '#table1',
                //url: '__STATIC__/json/menus.json',
                  url: '{:url('menujsondata')}',
                toolbar:'#toolbarDemo',
                page: false,
		            cols: [[
		                {type: 'checkbox'},
		                {field: 'title', minWidth: 200, title: '名稱'},
		                {field: 'sort', width: 80, align: 'center', title: '排序號'},
		                {field: 'hide', width: 80, align: 'center', templet: function (d) {
		                        if (d.hide == 1) {
		                            return '<span class="layui-badge layui-bg-blue">隱藏</span>';
		                        } else {
		                            return '<span class="layui-badge-rim">顯示</span>';
		                        }
		                    }, title: '顯隱'
		                },
		                {templet: '#auth-state', width: 120, align: 'center', title: '操作'}
		            ]],
                done: function () {
                    layer.closeAll('loading');
                }
            });
        };

        renderTable();

        //全部展開
        $(document).on("click","#btn-expand",function(){
            treetable.expandAll('#table1');
        });

        //全部摺疊
        $(document).on("click","#btn-fold",function(){
            treetable.foldAll('#table1');
        });

        //重新整理表格
        $(document).on("click","#btn-refresh",function(){
            renderTable();
        });
        //搜尋
        $(document).on("click","#btn-search",function(){
            var keyword = $('#edt-search').val();
            var searchCount = 0;
            $('#table1').next('.treeTable').find('.layui-table-body tbody tr td').each(function () {
                $(this).css('background-color', 'transparent');
                var text = $(this).text();
                if (keyword != '' && text.indexOf(keyword) >= 0) {
                    $(this).css('background-color', 'rgba(250,230,160,0.5)');
                    if (searchCount == 0) {
                        treetable.expandAll('#table1');
                        $('html,body').stop(true);
                        $('html,body').animate({scrollTop: $(this).offset().top - 150}, 500);
                    }
                    searchCount++;
                }
            });
            if (keyword == '') {
                layer.msg("請輸入搜尋內容", {icon: 5});
            } else if (searchCount == 0) {
                layer.msg("沒有匹配結果", {icon: 5});
            }
        });
        
  //頭工具欄事件
  table.on('toolbar(table1)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
   
    switch(obj.event){
      case 'add':
						layer.ready(function(){ 
							  layer.open({
								type: 2,
								title: '增加',
								maxmin: true,
								area: ['80%', '70%'],
								content: '{:url('add')}',
								cancel: function(){ //重新整理網頁
								      //重新載入表格資料  
											 self.location='{:url('index')}';
								  }
							  });
						});
         //layer.msg('增加' + obj.config.id);
      break;
      case 'edit':
				         var data = checkStatus.data;
				         var dataall = '';
				         //data = JSON.stringify(data);
					      //迴圈把所有要刪除的ID整成12,13,545
								  for(var i=0;i<data.length;i++){
										 dataall += data[i].id+",";
									}
									dataall=dataall.substring(0,dataall.length-1)
				         
				//         console.log(dataall)
				//         layer.alert(dataall);
      break;
      case 'del':
				         var data = checkStatus.data;
				         var dataall = '';
				         //data = JSON.stringify(data);
					      //迴圈把所有要刪除的ID整成12,13,545
								  for(var i=0;i<data.length;i++){
										 dataall += data[i].id+",";
									}
									dataall=dataall.substring(0,dataall.length-1)
				         
				//         console.log(dataall)
				         layer.alert(dataall);
      break;
    };
  });

        //監聽工具條
        table.on('tool(table1)', function (obj) {
            var data = obj.data;
            console.log(data)
            var layEvent = obj.event;

            if (layEvent === 'del') {
                layer.msg('刪除' + data.id);
            } else if (layEvent === 'edit') {
                layer.msg('修改' + data.id);
            }
        });

		
});
</script>
</body>
</html>

注意:

1、外掛路徑

2、資料來源的路徑

二、控制器程式碼

<?php
namespace app\admin\controller;
use think\Controller;
use think\Validate;
use think\Db;
use think\db\Where;

class Menu extends Common{
		
	/**
	 * 欄目列表
	 */
    public function index(){

//		$res = Db::name('menu')->where('level',1)->order('sort desc')->select(); 
//		menujson(0,'ok',$res); 	
		
        return $this->fetch();
    }
	/**
	 * 導航選單JSON資料
	 */
    public function menujsondata(){

		$res = Db::name('menu')->select(); 
		foreach($res as $k => $rs){
				      $data[$k]['id']=$rs['id'];
				      $data[$k]['title']=$rs['title'];
				      $data[$k]['sort']=$rs['sort'];//排序
				      $data[$k]['icon']=$rs['icon'];
					  $data[$k]['hide']=$rs['hide'];
					  $data[$k]['pid']=$rs['pid'];
		}
		json(0,'',$count,$data); 	
		
    }
	/**
	 * 新增欄目、儲存
	 */
    public function add(){
    	
 			$id=input('id');
			$pid=input('pid');
			
		    //$level1=input('level');
			//$level=input('level');
			//$this->assign('level',$level);
			//當前
			//$level2=input('level');
			//$this->assign('level2',$level2);
//			$levelx=$level+1;
//			$this->assign('levelx',$levelx);
			//取得一級欄目
		   //$column_rs=Db::name('column')->where('level',$level1)->order('sort','desc')->select();
		   //$this->assign('column_rs',$column_rs);
		
//			$res = Db::name('menu')->where('level',1)->order('sort desc')->select();  
//		    $this->assign('name',$data);  
		   
		   if($id){
	           $rs=Db::name('menu')->field('id,level,pid,title,position,hide,sort')->where('id',$id)->find();
			   $this->assign('rs',$rs);
		   }
		
			if (request()->isPost()){

				
					//$title=input('title');
				    $data = input('post.');
				    if(!$data['pid']){
				    	$data['pid']= -1;
				    }
					$validate = Validate::make([
						'title'  => 'require|max:30',
					]);

					if (!$validate->check($data)) {
					   $this->error('錯誤:'.$validate->getError());
					}
					$rsi=db('menu')->insert($data);
					
					if($rsi){
						$this->success('成功!',url('add',['pid'=>$pid,'level'=>$level-2]));
					}else{
						$this->error('失敗');
					}

				return;
			}
        return $this->fetch();
    }
	


}

三、資料庫

例子: TP5.1 + Layui 2.4.0(增強版)(完全程式碼)

1、模板

<!DOCTYPE html>
<html>				
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>導航選單</title>
	<link rel="stylesheet" href="__STATIC__/layui/css/layui.css" media="all">
	<script src="__STATIC__/layui/layui.js"></script> 
	<link rel="stylesheet" href="__ADMIN__/css/index.css" media="all">
	<script type="text/javascript" src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
	<link rel="stylesheet" href="__ADMIN__/css/font-awesome.css">
	<style>
		
	</style>
</head>
<body style="background-color: #FFFFFF;">
<!-- 你的HTML程式碼 -->
<!-- 表格 -->
<div class="layui-fluid">
<!-- 操作列 -->
<div id="m_id">
    <table class="layui-hidden" id="treeTable" lay-filter="treeTable"></table>
</div>
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-group">
  <button class="layui-btn layui-btn-primary layui-btn-xs" onclick="add(null);"><i class="layui-icon layui-icon-add-1"></i>增加</button>
  <button class="layui-btn layui-btn-primary layui-btn-xs" id="btn-fold" data-id="1"><i class="layui-icon layui-icon-align-left"></i>摺疊/展開</button>
  <button class="layui-btn layui-btn-primary layui-btn-xs" onclick="refresh();"><i class="layui-icon layui-icon-edit"></i>重新整理</button>
  <button class="layui-btn layui-btn-primary layui-btn-xs" onclick="delAll();"><i class="layui-icon layui-icon-delete"></i>刪除</button>
</div>
</script>
<script type="text/html" id="auth-state">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a>
</script>
<!-- 這裡的 顯示/隱藏 -->
<script type="text/html" id="switchTpl">
  <input type="checkbox" name="hide" value="{{d.id}}" lay-skin="switch" lay-text="隱藏|顯示" lay-filter="sexDemo" {{ d.hide == 1 ? 'checked' : '' }}>
</script>
<!-- 位置 -->
<script type="text/html" id="positionTpl">
  {{#  if(d.position == 2){ }}
               <span style="color: #01AAED;"> 底部</span>
  {{#  } else if(d.position == 3) { }}
                <span style="color: #FF5722;">都在</span>
  {{#  } else { }}
                頂部
  {{#  } }}
</script>
<!-- 表格end -->
<script>
    var editObj=null,ptable=null,treeGrid=null,tableId='treeTable',layer=null;
    layui.config({
        base: '__STATIC__/menu/treegrid/'
    }).extend({
        treeGrid:'treeGrid'
    }).use(['jquery','treeGrid','layer', 'table'], function(){
						        var $=layui.jquery;
						        table = layui.table;
						        treeGrid = layui.treeGrid;//很重要
						        form = layui.form;
						        layer=layui.layer;
						        
						        ptable=function(){ 
								       treeGrid.render({
										            id:tableId
										            ,elem: '#'+tableId
										            //,height: '' //固定值
										            ,idField:'id'
										            //,url:'__STATIC__/json/treegrid_data.json'
										            ,url:'{:url('menujsondata')}'
										            ,toolbar:'#toolbarDemo'
										            ,cellMinWidth: 100
										            ,treeId:'id'//樹形id欄位名稱
										            ,treeUpId:'pId'//樹形父id欄位名稱
										            ,treeShowName:'name'//以樹形式顯示的欄位
										            ,cols: [[
										                {type:'checkbox'}
										                ,{width:60,title: '增加', align:'center'/*toolbar: '#barDemo'*/
										                    ,templet: function(d){
										                    var html='';
										                    var addBtn='<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="add">新增</a>';
										                    return addBtn;
										                    }
										                }
										                //,{field:'id',width:70, title: 'id'}
										                ,{field:'sort', edit:'text',width:70, title: '排序'}
										                ,{field:'name', edit:'text', title: '名稱'}
										                //,{field:'icon', title: '圖示', event: 'addIcon', style:'cursor: pointer;'}
										                ,{field:'url', edit:'text', title: 'pid',width:180, title: '網址'}
										                ,{field:'icon', title: '圖示', event: 'addIcon', style:'cursor: pointer;', width: 60
																      ,templet: function(d){
																        return '<i class="fa fa-'+ d.icon +'" style="font-size: 20px; color: #1E9FFF;"></i>'
																      }
																    }
																		,{field:'position', title: '位置', event: 'addPosition', style:'cursor: pointer;', width: 60, templet: '#positionTpl'}
										                ,{field:'hide', title:'顯/隱', width:85, templet: '#switchTpl', unresize: true}
										                ,{templet: '#auth-state', width: 70, align: 'center', title: '操作'}
										            ]]
										            ,page:false
								        });
						        
						         }; 
						         
						         ptable();

			        //摺疊/展開
			        $(document).on("click","#btn-fold",function(){
			        	  var map=treeGrid.getDataMap(tableId);
			        	  var data_id2 = $(this).attr("data-id") 
			        	  var m;
			        	  if(data_id2 == 1){
			        	  	m = true;;
			        	  	$(this).attr("data-id",2) 
			        	  }else if(data_id2 == 2){
			        	  	m = false;
			        	  	$(this).attr("data-id",1) 
			        	  };
			        	  
		                	// console.log(map)
			        	   $.each(map, function(i) {
			        	   		if(map[i].pId){ 
			        	   			 
			        	   			var a = map[i].pId; 
			 									var o= map[a];   
			        	   			treeGrid.treeNodeOpen(o,m);
			 									
			 									
//			        	   			treeGrid.treeNodeOpen(o,!o.is_open);
			        	   		}
			        	   });
			        });
			
			        treeGrid.on('tool('+tableId+')',function (obj) {
			        	 
					            if(obj.event === 'del'){
					            	 console.log(obj)
					            	//刪除行
					                del(obj);
					            }else if(obj.event==="add"){
					            	 //新增行
					                add(obj);
					            }else if(obj.event==="addIcon"){
					            	 //新增圖示
					                addicon(obj);
					            }else if(obj.event==="addPosition"){
					            	 //新增位置
					                addPosition(obj);
					            }
			        });
			        
		//更新 顯示/隱藏  操作
					  form.on('switch(sexDemo)', function(obj){
					       //layer.tips(this.value + ' ' + this.name + ':'+ obj.elem.checked, obj.othis);
					       console.log(this.value + '|' + this.name + ':'+ obj.elem.checked, obj.othis)
					       var id=this.value;
					       var field=this.name;
					       var value = obj.elem.checked;
							       if(value){
							       	  value =1;
							       }else{
							       	  value =0;
							       }
					       //console.log(value);
											//更新後臺資料
													 $.ajax({
																	 type: "post",
																	 url: "{:url('edit')}",
																	 data: {id:id,title:value,field:field,action:'ajax_update'},
																		success:function(data){
																		     layer.msg(data['msg']);
																		},
																		error:function(){
																		  layer.msg('更新失敗!');
																		}
													 });
					  }); 
  
			        
    });
//單個刪除
    function del(obj) {
    	
        var pdata=obj?obj.data:null;
        //alert(pdata.id)
        layer.confirm("你確定刪除資料嗎?如果存在下級節點則一併刪除,此操作不能撤銷!", {icon: 3, title:'提示'},
            function(index){
            	//確定回撥
                obj.del();
											//更新後臺資料
													 $.ajax({
																	 type: "post",
																	 url: "{:url('del')}",
																	 data: {id:pdata.id},
																		success:function(data){
																				 if(data[0]==1){
																					    layer.msg(data[1]);
												                     // self.location='{:url('index')}';
																					}else{
																						layer.msg('失敗!'+data[1]);
																						 //table.render({});//重新渲染
																					}
																		},
																		error:function(){
																		  layer.msg('更新失敗!');
																		}
													 });
                layer.close(index);
            },function (index) {
            	//取消回撥
               layer.close(index);
            }
        );
    }


    var i=1000;
//新增
    function add(pObj) {
    	
    	  //console.log(pObj)
        var pdata=pObj?pObj.data:null;
        //console.log(pdata);
        var param={};
        param.name='請修改標題';
        //param.id=++i;
        param.pId=pdata?pdata.id:null;
//      treeGrid.addRow(tableId,pdata?pdata.LAY_TABLE_INDEX+1:0,param);
				//更新後臺資料
						 $.ajax({
										 type: "post",
										 url: "{:url('add')}",
										 data: {id:param.id,pid:param.pId,title:param.name,action:'ajax_add'},
										 success: function(data){
											 layer.msg(data['msg']);
											 var id=154;
											 
												//param.name='請修改標題';
								        param.id=data['menuid'];
								        //param.pId=pdata?pdata.id:null;
								        treeGrid.addRow(tableId,pdata?pdata.LAY_TABLE_INDEX+1:0,param);
											  //執行過載
											  //ptable()
											
										},
										error: function(){
												layer.msg('更新失敗!');
										}
						 });
    }

//更新圖示
    function addicon(pibj) {
    	
   	  //console.log(pObj)
        var pdata=pibj?pibj.data:null;
        //console.log(pdata);
        //console.log(pdata.id);
					layer.ready(function(){
						  layer.open({
							type: 2,
							title: '更新圖示',
							maxmin: true,
							area: ['80%', '70%'],
							content: '{:url('add')}?action=ajax_update&field=icon&id='+pdata.id,
							cancel: function(){ //重新整理網頁
							      //重新載入表格資料
										//self.location='{:url('index')}';
										ptable()
							  }
						  });
					});
    }
//更新位置
    function addPosition(ppbj) {
    	
   	  //console.log(pObj)
        var pdata=ppbj?ppbj.data:null;
        //console.log(pdata);
        //console.log(pdata.id);
					layer.ready(function(){
						  layer.open({
							type: 2,
							title: '更新位置',
							maxmin: true,
							area: ['80%', '70%'],
							content: '{:url('add')}?action=ajax_update&field=position&id='+pdata.id,
							cancel: function(){ //重新整理網頁
							      //重新載入表格資料
										ptable()
							  }
						  });
					});
    }

    function print() {
        console.log(treeGrid.cache[tableId]);
        var loadIndex=layer.msg("物件已列印,按F12,在控制檯檢視!", {
            time:3000
            ,offset: 'auto'//頂部
            ,shade: 0
        });
    }
    
 //重新整理
    function refresh() { 
        	ptable()
    }
    
//批量刪除
    function delAll() { 
        //alert('1')
							    var checkStatus = treeGrid.checkStatus(tableId)
							    //console.log(JSON.stringify(data))
								  var dataall='';
								  data = checkStatus.data;
							 
								  //迴圈把所有要刪除的ID整成12,13,545
								  for(var i=0;i<checkStatus.data.length;i++){
										 dataall += data[i].id+",";
									}
									dataall=dataall.substring(0,dataall.length-1)
									//alert(dataall)
									 //layer.alert(dataall);
										 layer.confirm('真的刪除行麼', function(index){
												//obj.del();
												//id= data.id;
														layer.close(index);
															 $.ajax({
																	url:'{:url('del')}',
																	type:"post",
																	data:{id:dataall},
																	async:true,
																	success:function(data){
																	     if(data[0]==1){
																		      layer.msg(data[1]);
																		    //table.reload(treeTable)
									                      //self.location='{:url('index')}';
																				}else{
																					layer.msg('失敗!'+data[1]);
																					 //
																				}
																				//table.reload(treeTable)
																				ptable()
																		
																	},
																	error:function(){
																	  layer.msg('頁面跳轉失敗!');
																	}
															});
								      });
    }
        
//  function openorclose() {
//      var map=treeGrid.getDataMap(tableId);
//      //var o= map['257','259'];
//       
//      
//      treeGrid.treeNodeOpen(o,!o.is_open);
//  }

    function getCheckData() {
        var checkStatus = treeGrid.checkStatus(tableId)
            ,data = checkStatus.data;
        layer.alert(JSON.stringify(data));
    }
    function getCheckLength() {
        var checkStatus = treeGrid.checkStatus(tableId)
            ,data = checkStatus.data;
        layer.msg('選中了:'+ data.length + ' 個');
    }
</script>
</body>
</html>

2、控制器程式碼

<?php
namespace app\admin\controller;
use think\Controller;
use think\Validate;
use think\Db;
use think\db\Where;

class Menu extends Common{
		
	/**
	 * 欄目列表
	 */
    public function index(){

//		$res = Db::name('menu')->where('level',1)->order('sort desc')->select(); 
//		menujson(0,'ok',$res); 	
		
        return $this->fetch();
    }
	/**
	 * 導航選單JSON資料
	 */
    public function menujsondata(){

		$res = Db::name('menu')->order('sort', 'desc')->select(); 
		$count = count($res);
		foreach($res as $k => $rs){
				      $data[$k]['id']=$rs['id'];
				      $data[$k]['name']=$rs['title'];
				      
				      //先判斷是否有下級資料  有則加上引數is_open
						      $where1['pid']=$rs['id'];
						      $checkRepeat=checkRepeat('menu',$where1,0);//一種有條件(比如自身修改)的查詢重複
						      if($checkRepeat){
						           $data[$k]['is_open']=false;//true=展開  false=收起 
						      }
						      
				      $data[$k]['sort']=$rs['sort'];//排序
				      $data[$k]['icon']=$rs['icon'];
					  $data[$k]['hide']=$rs['hide'];
					  $data[$k]['position']=$rs['position'];
					  $data[$k]['pId']=$rs['pid'];
		}
		json(0,'',$count,$data); 	
		
    }
	/**
	 * 新增欄目、儲存
	 */
    public function add(){
    	
 			$id=input('id');
 			$this->assign('id',$id);
			$pid=input('pid');
			$title=input('title');
			$action=input('action');
			$this->assign('action',$action);
			$field=input('field');
			$this->assign('field',$field);
			
			if($id){//更新圖示要用
					//列出資料
					$rs=Db::name('menu')->field('id,icon,position')->where('id',$id)->find();
					$this->assign('rs',$rs);
			}
			
			//ajax 更新標題
		 			if($action=="ajax_add"  && $title){
		 				      // echo ($id."|".$pid."|".$title);die;
		 				
		 				   $data_ajax['title']=$title;
		 				   if($pid){
		 				   	   $data_ajax['pid']=$pid;
		 				   }
		 				   
						     //$rs=db('menu')->insert($data_ajax);
						     $menuid=db('menu')->insertGetId($data_ajax);
		
							
							if($menuid){
								$arr['code']=1;
								$arr['msg']="新增成功";
								$arr['title']=$title;
								$arr['menuid']=$menuid;
								 //$se="更新成功";
							}else{
								$arr['code']=2;
								$arr['msg']="新增失敗";
								$arr['title']=$title;
								$arr['menuid']='';
							}
							return $arr;die;
		 			}
			
		    //$level1=input('level');
			//$level=input('level');
			//$this->assign('level',$level);
			//當前
			//$level2=input('level');
			//$this->assign('level2',$level2);
//			$levelx=$level+1;
//			$this->assign('levelx',$levelx);
			//取得一級欄目
		   //$column_rs=Db::name('column')->where('level',$level1)->order('sort','desc')->select();
		   //$this->assign('column_rs',$column_rs);
		
//			$res = Db::name('menu')->where('level',1)->order('sort desc')->select();  
//		    $this->assign('name',$data);  
		   
//		   if($id){
//	           $rs=Db::name('menu')->field('id,level,pid,title,position,hide,sort')->where('id',$id)->find();
//			   $this->assign('rs',$rs);
//		   }
//		
//			if (request()->isPost()){
//
//				
//					//$title=input('title');
//				    $data = input('post.');
////				    if(!$data['pid']){
////				    	$data['pid']= -1;
////				    }
//					$validate = Validate::make([
//						'title'  => 'require|max:30',
//					]);
//
//					if (!$validate->check($data)) {
//					   $this->error('錯誤:'.$validate->getError());
//					}
//					$rsi=db('menu')->insert($data);
//					
//					if($rsi){
//						$this->success('成功!',url('add',['pid'=>$pid,'level'=>$level-2]));
//					}else{
//						$this->error('失敗');
//					}
//
//				return;
//			}
        return $this->fetch();
    }
	
	/**
	 * 編輯欄目、儲存
	 */
    public function edit(){
    	    $action=input('action');
 			$id=input('id');
 			$field=input('field');

			$title=input('title');
			$icon=input('icon');
			$url=input('url');
			$sort=input('sort');
			$hide=input('hide');
			//$position=input('position');
			//dump($title);die;
			//$spread=input('spread');
			//$controller=input('controller');
			$pid=input('pid');

			
			
			//ajax 更新標題
 			if($action=="ajax_update" && $id){//更新欄位值
 				
	 				$field=$field=="name"?"title":$field;//當欄位是name是要轉換成資料庫對應的欄位title
					$rs=Db::name('menu')->where('id', $id)->update([$field => $title]);

					
					if($rs){
						$arr['code']=1;
						$arr['msg']="更新成功";
						$arr['title']=$title;
						 //$se="更新成功";
					}else{
						$arr['code']=2;
						$arr['msg']="更新失敗";
						$arr['title']=$title;
					}
					
					if($field=="icon" || $field=="position"){//更新icon圖示、位置
						return $arr['msg'];die;
					}else{
						return $arr;die;
					}
					
						
 				
 			}

			
////			if($pid=="a"){
////				$pid=0;
////			}
//			$level=input('level');
//
//			if(!$id){
//				$this->error('錯誤:ID非空!');
//			}
//
//			if (request()->isPost()){
//
//				$rs=Db::name('column')
//				    ->where('id', $id)
//				    ->update(['title' => $title,'icon' => $icon,'url' => $url,'sort' => $sort,'hide' => $hide,'position' => $position,'spread' => $spread,'controller' => $controller,'pid' => $pid]);
//
//					
//					if($rs){
//						//$this->success('成功!',url('add'));
//						 $this->success('成功!',url('column/add',['id'=>$id,'pid'=>$pid,'level'=>$level-1]));
//					}else{
//						$this->error('失敗!');
//					}
//
//				return;
//			}
//     // return $this->fetch();
//     return view(add);
    }

	
//欄目列表 讀出介面資料
	public function columntable()
	{
		$pid=input('pid');
		$flid=input('flid');
		$ts_id=input('ts_id');//上報教學站
		$page=input('page');//頁數
		$limit=input('limit');//一頁多少條記錄
		$type=input('type');//搜尋分類
		$key=input('key');//搜尋關鍵詞

        $where = new Where;
		if($key==""){//不搜尋
				//級別
			   if($pid){
					$where['pid'] = $pid;
				}else{
					$where['pid'] = 0;
				}
		}else{//搜尋
		
				//類別
			   if($type=="id"){
					$where[$type] = $key;
				}else{
					$where['flid'] = $flid;
					$where[$type] = ['like',"%".$key."%"];
				}
		}
		
		$rs=Db::name('menu')->where($where)->order('id desc')->limit($limit)->page($page)->select();
		$rs1=Db::name('menu')->where($where)->select();

		$count = count($rs1);//取得記錄集總條數
		json(0,'資料返回成功',$count,$rs); 

	}


//通用刪除
	public function del(){
		
			$id=input('id');//id
			$dataname="menu";//表名
			if(!$id && !$dataname){
				$this->error('錯誤:引數不為空!');
			}
			$del_info=del($dataname,$id,1,$dataname,'pid');
			$del_info = explode(',',$del_info);  
			if($del_info[0]==1){//1=成功
				$date=[1,$del_info[1]];
			}elseif($del_info[0]==2){//失敗
				$date=[0,$del_info[1]];
			}
            return $date;
	}
	
//圖示
	public function icon(){
		
		return $this->fetch();
	}


}

3、treeTable外掛程式碼有修改

外掛放置路徑按上面例子放

修改dltable.js位置:

1、增加修改欄位引數

that.layBody.on('change', '.'+ELEM_EDIT, function(){

2、原始碼有BUG,如果第一個陣列PID有值,就只會顯示一條資料

Class.prototype.resetData=function(list) {

4、edu_menu表程式碼

/*
Navicat MySQL Data Transfer

Source Server         : 本機
Source Server Version : 50553
Source Host           : localhost:3306
Source Database       : edu_cms

Target Server Type    : MYSQL
Target Server Version : 50553
File Encoding         : 65001

Date: 2018-09-01 16:26:08
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `edu_menu`
-- ----------------------------
DROP TABLE IF EXISTS `edu_menu`;
CREATE TABLE `edu_menu` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `model` tinyint(11) DEFAULT '1' COMMENT '模型 1產品(要購買) 2文章 3單頁 4bbs 5留言 6招聘',
  `icon` varchar(100) DEFAULT NULL COMMENT '圖示',
  `title` varchar(30) DEFAULT NULL COMMENT '標題',
  `pid` int(11) DEFAULT NULL COMMENT '父類id',
  `pid_all` varchar(300) DEFAULT NULL COMMENT '所有上級的父類id  18,19,15',
  `hide` tinyint(1) DEFAULT '0' COMMENT '顯示是否 0顯示 1隱藏',
  `url` varchar(150) DEFAULT NULL COMMENT '連結',
  `sort` int(11) DEFAULT '0' COMMENT '排序',
  `level` int(11) DEFAULT '0' COMMENT '層次',
  `position` tinyint(4) DEFAULT '1' COMMENT '位置 1頂部 2底部 3都在',
  `enterprise_id` int(11) DEFAULT NULL COMMENT '企業ID',
  `add_user_id` int(11) DEFAULT NULL COMMENT '新增者ID',
  `time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '建立時間',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=445 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of edu_menu
-- ----------------------------
INSERT INTO `edu_menu` VALUES ('433', '1', null, '人力', '377', '377', '0', null, '0', '1', '1', null, null, '2018-09-01 15:52:00');
INSERT INTO `edu_menu` VALUES ('431', '1', null, '會計', '377', '377', '0', null, '0', '1', '1', null, null, '2018-09-01 15:52:05');
INSERT INTO `edu_menu` VALUES ('291', null, 'thermometer-0', '圖書商城', null, null, '0', '', '1', '0', '1', null, null, '2018-08-31 18:45:19');
INSERT INTO `edu_menu` VALUES ('432', '1', null, '教師', '377', '377', '0', null, '0', '1', '1', null, null, '2018-09-01 15:52:03');
INSERT INTO `edu_menu` VALUES ('327', null, null, '錄播課程', null, null, '0', null, '10', '0', '2', null, null, '2018-08-31 18:19:32');
INSERT INTO `edu_menu` VALUES ('435', '1', null, '行業新聞', '382', '382', '0', null, '0', '1', '1', null, null, '2018-09-01 15:52:18');
INSERT INTO `edu_menu` VALUES ('342', null, null, '首頁', null, null, '0', null, '300', '0', '1', null, null, '2018-08-31 19:16:28');
INSERT INTO `edu_menu` VALUES ('419', '1', null, '中學', '417', '349,417', '0', null, '0', '2', '1', null, null, '2018-09-01 15:50:23');
INSERT INTO `edu_menu` VALUES ('418', '1', null, '小學', '417', '349,417', '0', null, '0', '2', '1', null, null, '2018-09-01 15:50:25');
INSERT INTO `edu_menu` VALUES ('439', '1', null, '公司簡介', '384', '384', '0', null, '0', '1', '1', null, null, '2018-09-01 15:52:41');
INSERT INTO `edu_menu` VALUES ('349', '3', null, '直播課程', null, null, '1', null, '200', '0', '3', null, null, '2018-09-01 12:47:42');
INSERT INTO `edu_menu` VALUES ('427', '1', null, 'JS教程', '426', '291,426', '0', null, '0', '2', '1', null, null, '2018-09-01 15:51:39');
INSERT INTO `edu_menu` VALUES ('438', '1', null, '請修改標題', '384', '384', '0', null, '0', '1', '1', null, null, '2018-09-01 15:52:33');
INSERT INTO `edu_menu` VALUES ('357', null, null, '請修改標題2', '355', null, '0', null, '0', '0', '1', null, null, '2018-08-31 10:12:50');
INSERT INTO `edu_menu` VALUES ('421', '1', null, '中學2', '420', '327,420', '0', null, '0', '2', '1', null, null, '2018-09-01 15:50:56');
INSERT INTO `edu_menu` VALUES ('420', '1', null, '教師1', '327', '327', '0', null, '0', '1', '1', null, null, '2018-09-01 15:50:45');
INSERT INTO `edu_menu` VALUES ('417', '1', null, '教師', '349', '349', '0', null, '0', '1', '1', null, null, '2018-09-01 15:50:17');
INSERT INTO `edu_menu` VALUES ('377', null, null, '講師團隊', null, null, '0', null, '0', '0', '1', null, null, '2018-08-31 18:48:39');
INSERT INTO `edu_menu` VALUES ('434', '1', null, '公司新聞', '382', '382', '0', null, '0', '1', '1', null, null, '2018-09-01 15:52:20');
INSERT INTO `edu_menu` VALUES ('382', null, null, '新聞資訊', null, null, '0', null, '0', '0', '1', null, null, '2018-08-31 19:07:03');
INSERT INTO `edu_menu` VALUES ('384', null, null, '關於我們', null, null, '0', null, '0', '0', '1', null, null, '2018-08-31 19:08:15');
INSERT INTO `edu_menu` VALUES ('428', '1', null, 'PHP教程', '426', '291,426', '0', null, '0', '2', '1', null, null, '2018-09-01 15:51:30');
INSERT INTO `edu_menu` VALUES ('426', '1', null, '計算機', '291', '291', '0', null, '0', '1', '1', null, null, '2018-09-01 15:51:26');
INSERT INTO `edu_menu` VALUES ('414', '1', null, '請修改1', '413', '349,413', '0', null, '0', '2', '1', null, null, '2018-09-01 15:49:19');
INSERT INTO `edu_menu` VALUES ('413', '1', null, '自考', '349', '349', '0', null, '0', '1', '1', null, null, '2018-09-01 15:49:01');
INSERT INTO `edu_menu` VALUES ('415', '1', null, '本科', '413', '349,413', '0', null, '0', '2', '1', null, null, '2018-09-01 15:49:16');
INSERT INTO `edu_menu` VALUES ('416', '1', null, '專科', '413', '349,413', '0', null, '0', '2', '1', null, null, '2018-09-01 15:49:12');
INSERT INTO `edu_menu` VALUES ('422', '1', null, '小學2', '420', '327,420', '0', null, '0', '2', '1', null, null, '2018-09-01 15:50:51');
INSERT INTO `edu_menu` VALUES ('423', '1', null, '自考1', '327', '327', '0', null, '0', '1', '1', null, null, '2018-09-01 15:51:06');
INSERT INTO `edu_menu` VALUES ('424', '1', null, '研究生', '423', '327,423', '0', null, '0', '2', '1', null, null, '2018-09-01 15:51:14');
INSERT INTO `edu_menu` VALUES ('425', '1', null, '博士', '423', '327,423', '0', null, '0', '2', '1', null, null, '2018-09-01 15:51:10');
INSERT INTO `edu_menu` VALUES ('429', '1', null, '自考', '291', '291', '0', null, '0', '1', '1', null, null, '2018-09-01 15:51:43');
INSERT INTO `edu_menu` VALUES ('430', '1', null, '專科升本科密級', '429', '291,429', '0', null, '0', '2', '1', null, null, '2018-09-01 15:51:48');
INSERT INTO `edu_menu` VALUES ('436', '1', null, '公告', '382', '382', '0', null, '0', '1', '1', null, null, '2018-09-01 15:52:16');
INSERT INTO `edu_menu` VALUES ('440', '1', null, '公司地址', '384', '384', '0', null, '0', '1', '1', null, null, '2018-09-01 15:52:39');
INSERT INTO `edu_menu` VALUES ('441', '1', null, '聯絡我們', '384', '384', '0', null, '0', '1', '1', null, null, '2018-09-01 15:52:37');

呼叫方法:

控制程式碼:

		    		$res = Db::name('menu')->field('id as value,title as name,pid')->whereNull('pid')->order(['sort'=>'desc'])->select(); 
		    		foreach($res as $k => $rs){
 
							 $rs['children']=getList2($rs['value']);
							 $res[$k]= $rs;
		    		}
		    		
		    		echo json_encode($res);

getList2函式

/**
* 無限級分類
* getList2返回的資料都是二級、3級、4級、5級、6級等資料;一級在呼叫那邊實現
* 導航選單引用
*/
function getList2($id) {
		$tree = '';
		$list=Db::name('menu')->field('id as value,title as name,pid')->where('pid',$id)->select();
		foreach($list as  $key => $val ){
			if($val['pid']!=0){
				$val['children'] = getList2($val['value']);
				$tree[] = $val;
			}
				
		}
		
		return $tree;
		//echo json_encode($tree); 
}

模板程式碼:

  <div class="layui-form-item">
    <label class="layui-form-label">分類</label>
    <div class="layui-input-block">
						<select name="city" xm-select="select15_2">
							<option value="">請選擇, 此處是聯動多選</option>
						</select>
    </div>
  </div>
<!-- 引入分類 多選樣式 開始 -->
<script type="text/javascript" src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="__STATIC__/menu/formSelects/formSelects-v4.css"/>
<script src="__STATIC__/menu/formSelects/formSelects-v4.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
      var formSelects = layui.formSelects;
			
			formSelects.config({
				success: function(id, url, val, result){
					console.log("success回撥: " + url, id);
				},
				error: function(id, url, val, err){
					console.log("err回撥: " + url, id);
				}
			});
			formSelects.data('select15_2', 'server', {
				  type: "post",
			    url: '{:url('menu/menujsondata')}',
			    data:{action:'category'},
			    linkage: true,
			    linkageWidth: 130,
			});
     
</script>
<!-- 引入分類 多選樣式 結束 -->
/**
* 格式函式  專門把資料錄格式成為layui 資料表格的格式
*/
function json($code,$msg="",$count,$data=array()){  
            $result=array(  
              'code'=>$code,  
              'msg'=>$msg, 
			  'count'=>$count,  
              'data'=>$data   
            );  
            //輸出json  
            echo json_encode($result);  
            exit;  
}