BootStrap-Table-Treegrid樹形表格使用指南

BootStrap-bable-treegrid

Bootstrap是目前很流行的一款前端框架,也有很多第三方基於Bootstrap開發出了很多跟實用性的一些功能,比如BootStrap-bable-treegrid樹形表格。樹形表格在開發中應該是很常用到的。

引入樣式文件

<link rel="stylesheet" href="static/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="static/bootstrap-table/dist/bootstrap-table.css" />
<link rel="stylesheet" href="static/bootstrap-table/dist/extensions/treegrid/treegrid.css" />
<script src="static/bootstrap/dist/js/jquery.js" ></script>
<script src="static/bootstrap/dist/js/bootstrap.js" ></script>
<script src="static/bootstrap-table/dist/bootstrap-table.js" ></script>
<script src="static/bootstrap-table/dist/locale/bootstrap-table-zh-CN.js" ></script>
<script src="static/bootstrap-table/dist/extensions/treegrid/bootstrap-table-treegrid.js" ></script>
<script src="static/bootstrap-table/dist/extensions/treegrid/jquery.treegrid.js" ></script>
<script src="static/combotree/bootstrap-treeview.js" ></script>
<script src="static/combotree/combotree.js" ></script>

其中combotree.js是自己寫的一個js文件,用於下拉樹顯示。下面附有代碼。

頁面部分代碼(頁面只需要一個table標籤用於存放數據就可以了,可以自定義一些操作表格的按鈕,比如增刪改)。

<!-- 增刪改 -->
<div id="toolbar" class="btn-group">
    <button type="button" class="btn btn-default" onclick="btn_add()">
        <span class="glyphicon glyphicon-plus"></span>新增
    </button>
    <button type="button" class="btn btn-default" onclick="btn_edit()">
        <span class="glyphicon glyphicon-pencil"></span>修改
    </button>
    <button type="button" class="btn btn-default" onclick="btn_delete()">
        <span class="glyphicon glyphicon-remove"></span>刪除
    </button>
</div>

<table id="menu_table"></table>

JS部分代碼,獲取數據,渲染表格,其中的字段名需要和實體類中的字段名一樣。

var $table = $("#menu_table");

$("#menu_table").bootstrapTable({
    url: 'menu/list',    //表格數據請求地址
    toolbar: '#toolbar',    //自定義組件
    striped: true,	//隔行換色
    height: tableHeight(),		//設置高度
    pagination: false,	//顯示錶格的底部工具欄
    sidePagination: 'server',   //client客戶端分頁,server服務器分頁
    search: false,		//定義右上方的搜索框,輸入即可以開始搜索
    showColumns: true,	//選列的下拉菜單
    showRefresh: true,	//刷新按鈕
    showToggle: true,	//視圖切換
    toolbarAlign: 'left',	//自定義按鈕位置
    clickToSelect: true,	//點擊行選中
    singleSelect: true,		//單選
    // 設置樹狀表格參數
    treeShowField: 'name',
    sortName:'id',
    parentIdField: 'parentId',		//父節點id
    onLoadSuccess: function(data) {
        //console.log(data);
        $table.treegrid({
            initialState: 'expanded',//展開
            treeColumn: 1,//指明第幾列數據改爲樹形
            expanderExpandedClass: 'glyphicon glyphicon-triangle-bottom',
            expanderCollapsedClass: 'glyphicon glyphicon-triangle-right',
            onChange: function() {
                $table.bootstrapTable('resetWidth');
            }
        });
    },
    columns:[{
        checkbox: true    //多選框
    },{
        field: 'id',	//每列的字段名
        title: 'ID',	//表頭所顯示的名字
        halign: 'center',	//表頭的對齊方式
        valign: 'middle',	//表格對齊方式居中
        order: 'asc',		//默認排序方式
        sortable: true,		//設置可以排序
        align: 'center'		//表格數據對齊方式
    },{
        field: 'name',
        title: '名稱',
        halign: 'center',
        align: 'center'
    },{
        field: 'url',
        title: '路徑',
        halign: 'center',
        align: 'center'
    },{
        field: 'idx',
        title: '排序',
        halign: 'center',
        align: 'center'
    }]
});

function tableHeight() {
    return $(window).height() - 100;
}

後臺響應請求數據方法。

@RequestMapping(value="/list")
@ResponseBody
public Object list(TablePageable pageParam,TbMenuForm form) {
	Sort sort = pageParam.bulidSort();     //排序
	Specification<TbMenu> spec = buildSpec(form);    //配置查詢參數
	return baseService.findAll(spec,sort);
}

方法中TablePageable類是用於接收Bootstrap表格分頁和排序參數的一個工具類,類中的bulidSort方法是指定排序字段和排序規則。

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

/**
 * 分頁的一個工具類,接收分頁信息
 */
public class TablePageable{
	private Integer limit; //分頁
	private Integer offset;//首記錄號(從0開始)
	private String sort;   //排序字段
	private String order;  //順序,逆序
	
	public Integer getLimit() {
		return limit;
	}

	public void setLimit(Integer limit) {
		this.limit = limit;
	}

	public Integer getOffset() {
		return offset;
	}

	public void setOffset(Integer offset) {
		this.offset = offset;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	
	public PageRequest bulidPageRequest() {
		int page=(offset!=null&&limit!=null)?offset/limit:0;
		int size=limit!=null?limit:10;
		if(sort==null) {
			return PageRequest.of(page, size);
		}else {
			Order order2=new Order(Direction.fromString(order), sort);
			Sort sort2= Sort.by(order2);
			return PageRequest.of(page,size,sort2 );
		}
		
	}
	
	public PageRequest bulidPageable(Sort sort) {
		int page=(offset!=null&&limit!=null)?offset/limit:0;
		int size=limit!=null?limit:10;
		return PageRequest.of(page, size, sort);
	}
	
	public Sort bulidSort() {
		Order order2=new Order(Direction.fromString(order), sort);
		Sort sort2= Sort.by(order2);
		return sort2;
	}
}

這裏持久層查詢是用的Spring-Data-Jpa,如果是其他持久層框架,只要查詢後返回的JSON數據格式一致就可以了。

JSON數據格式如下,parentId爲父節點Id,和前面js中設置的一定要對應一樣,不然樹形結構顯示不出來。

注意:如果父節點爲空,parentId的值需要爲null,不能爲""空串,一個parentId類型爲Integer類型,爲空串的話,樹形結構顯示不出來。

加載完成後數據顯示的效果如下。

實體類代碼。

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.mcy.springbootsecurity.custom.BaseEntity;
import org.springframework.data.annotation.CreatedBy;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 菜單表
 * @author
 *
 */
@Entity
public class TbMenu {
    private Integer id;
	private String name;
	private String url;
	private Integer idx;
	@JsonIgnore
	private TbMenu parent;
	@JsonIgnore
	private List<TbMenu> children=new ArrayList<>();

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }


	@Column(unique=true)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Integer getIdx() {
		return idx;
	}

	public void setIdx(Integer idx) {
		this.idx = idx;
	}

	@ManyToOne
	@CreatedBy
	public TbMenu getParent() {
		return parent;
	}

	public void setParent(TbMenu parent) {
		this.parent = parent;
	}

	@OneToMany(cascade=CascadeType.ALL,mappedBy="parent")
	@OrderBy(value="idx")
	public List<TbMenu> getChildren() {
		return children;
	}

	public void setChildren(List<TbMenu> children) {
		this.children = children;
	}

	public TbMenu(Integer id) {
		super(id);
	}

	public TbMenu(){
		super();
	}

	public TbMenu(String name, String url, Integer idx, TbMenu parent, List<TbMenu> children) {
		this.name = name;
		this.url = url;
		this.idx = idx;
		this.parent = parent;
		this.children = children;
	}

	public TbMenu(Integer integer, String name, String url, Integer idx, TbMenu parent, List<TbMenu> children) {
		super(integer);
		this.name = name;
		this.url = url;
		this.idx = idx;
		this.parent = parent;
		this.children = children;
	}

	@Transient
	public Integer getParentId() {
		return parent==null?null:parent.getId();
	}
}

新增和修改方法,前臺JS代碼(因爲新增和修改是共用的一個頁面和一個方法,所以這裏放一起寫了)。

//新增
function btn_add(){
    var selectRows = $table.bootstrapTable('getSelections');
    var dialog = $('<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="myModalLabel"></div>');
    if(selectRows&&selectRows.length==1){
        var parentId=selectRows[0].id;
        dialog.load('menu/edit',{parentId:parentId});
    }else{
        dialog.load('menu/edit');
    }
    $("body").append(dialog);
    dialog.modal().on('hidden.bs.modal', function () {
        dialog.remove();
        $table.bootstrapTable('refresh');
    });
}

//修改
function btn_edit(){
    var str = $("#menu_table").bootstrapTable('getSelections');
    if(str.length != 1){
        bootbox.alert("請選中一行進行編輯");
        return ;
    }

    var dialog = $('<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="myModalLabel"></div>');
    var id = str[0].id;
    dialog.load("menu/edit?id="+id);
    /*添加到body中*/
    $("body").append(dialog);
    /*彈出模態框,綁定關閉後的事件*/
    dialog.modal().on('hidden.bs.modal', function () {
        //刪除模態框
        dialog.remove();
        $table.bootstrapTable('refresh');
    });
}

新增和修改的後臺請求方法,跳轉到新增修改頁面,通過id來判斷是修改還是新增,parentId判斷新增時是否勾選行,勾選後爲默認父級。

@Override
public void edit(TbMenuForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
    TbMenu model = new TbMenu();
    if(form.getId() != null) {
        model = menuService.findById(form.getId());
    }
    if(form.getParentId() != null) {
        model.setParent(new TbMenu(form.getParentId()));
    }
    map.put("model", model);
}

新增修改頁面代碼

<body>
    <form id="myForm" class="form-horizontal" role="form" >
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">操作</h4>
                </div>
                <div class="modal-body">

                    <!-- 以下爲要修改的的內容 -->
                    <input type="hidden" name="id" th:value="${model.id}" id="modelId">
                    <div class="form-group">
                        <label for="txt_parent" class="col-sm-2 control-label">上級菜單</label>
                        <div class="col-sm-9">
                            <input name="parentId" data-th-value="${model.parent==null?null:model.parent.id}" class="form-control" id="txt_parent">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="txt_name" class="col-sm-2 control-label">菜單名稱</label>
                        <div class="col-sm-9">
                            <input type="text" name="name" data-th-value="${model.name}" class="form-control" id="txt_name">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="txt_url" class="col-sm-2 control-label">訪問地址</label>
                        <div class="col-sm-9">
                            <input type="text" name="url" data-th-value=${model.url} class="form-control" id="txt_url" placeholder="">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="txt_sort" class="col-sm-2 control-label">排序</label>
                        <div class="col-sm-9">
                            <input type="text" name="idx" data-th-value="${model.idx}" class="form-control" id="txt_sort">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="btnSubmit()" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>保存</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>關閉</button>
                </div>
            </div>
        </div>
    </form>
</body>

JS部分代碼。

<script th:inline="javascript">
    $(function(){
        $('#txt_parent').bootstrapCombotree({
            url:'menu/treedata?id='+$('#modelId').val()
        });

        $('.selectpicker').selectpicker({});
    });
    
    function btnSubmit() {
        var form= new FormData($("#myForm")[0]);
        $.ajax({
            url: 'menu/save',
            type: 'post',
            data: form,
            processData: false,  //不處理數據
            contentType: false,		//不設置內容類型
            success: function(result){
                if(result.success){
                    $("#myModal").modal("hide");
                    bootbox.alert("數據保存成功");
                }else{
                    bootbox.alert(result.msg);
                }
            },
            error: function(result){
                bootbox.alert("數據保存失敗!");
            }
        })
    }
</script>

頁面初始化後,加載Combotree下拉樹的數據,並初始化,後臺Combotree數據請求方法,如果是修改,就把當前修改項的id傳遞到後臺,代碼如下。

/***
 * combotree樹形加載
 * @return
 */
@RequestMapping(value="/treedata")
@ResponseBody
public Object treedata(Integer id) {
    Sort sort = Sort.by("idx");
    Specification<TbMenu> spec = buildSpec1();
    List<TbMenu> list = menuService.findAll(spec,sort);
    return buildTree(list,id);
}

private Object buildTree(List<TbMenu> list, Integer id) {
    List<HashMap<String, Object>> result=new ArrayList<>();
    for (TbMenu dept : list) {
        //判斷如果是修改,修改節點在下拉樹中不顯示
        if(dept.getId()!=id) {
            //因爲實體類中的字段名和需要返回的JSON字段名不同,這裏需要轉換一下
            HashMap<String, Object> node=new HashMap<>();
            node.put("id", dept.getId());
            node.put("text",dept.getName());
            node.put("pid", dept.getParentId());
            node.put("nodes",buildTree(dept.getChildren(), id));
            result.add(node);
        }
    }
    return result;
}

//條件查詢,先只顯示最上級的菜單,即parent父級節點爲空的數據
public Specification<TbMenu> buildSpec1() {
    Specification<TbMenu> specification = new Specification<TbMenu>() {

        private static final long serialVersionUID = 1L;

        @Override
        public Predicate toPredicate(Root<TbMenu> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            HashSet<Predicate> rules=new HashSet<>();
            Predicate parent = cb.isNull(root.get("parent"));
            rules.add(parent);
            return cb.and(rules.toArray(new Predicate[rules.size()]));
        }

    };
    return specification;
}

這裏持久層查詢是用的Spring-Data-Jpa,如果是其他持久層框架,只要查詢後返回的JSON數據格式一致就可以了。

響應請求數據返回的JSON格式數據,pid爲父節點id。

Combotree下拉樹,在前面還引入了一個自己寫的combotree.js文件,代碼如下。

(function ($) {
	function getTree(url){
		var result=$.ajax({
			type : 'post',
			url : url ,
			dataType : 'json' ,
			async : false
		}).responseText;
		
		return eval('('+result+')');
	}
	$.fn.extend({
		bootstrapCombotree: function(options, param){
			var self=this;
			this.onBodyDown=function(event){
				var $options=undefined;
				try{
					$options=$.data($(event.target).prev()[0],'bootstrapCombotree');
				}catch (e) {
					$options=undefined;
				}
				if (!($options!=undefined || event.target.id == 'comboDiv' || $(event.target).parents("#comboDiv").length>0)) {
				//if (!(event.target.id == 'comboDiv' || $(event.target).parents("#comboDiv").length>0)) {
					self.hideMenu();
				}
			}
			this.hideMenu=function(){
				$('#comboDiv').fadeOut('fast');
				$("#comboDiv").remove();
				$("body").unbind("mousedown", self.onBodyDown);
			}
			
			this.getNode=function(root,id){
				for(var i=0;i<root.length;i++){
					var node=root[i];
					if(node.id==id){
						return node;
					}
					var x=self.getNode(node.nodes?node.nodes:[],id);
					if(x){
						return x;
					}
				}
				return null;
			},
			
			this.create=function(target){
				var $self=$(target);
				var $option=$.data(target,'bootstrapCombotree').options;
				$self.attr("type","hidden");
				var $this=$('<input class="form-control" />');
				$this.attr('placeholder',$self.attr('placeholder'));
				$this.attr('readonly',true);
				$self.after($this[0]);
				//取出options
				var options=$.extend({},$option,{
					onNodeSelected:function(event,node){
						$self.val(node.id);
						$this.val(node.text);
						$('#comboDiv').fadeOut('fast');
						$("#comboDiv").remove();
						$("body").unbind("mousedown", self.onBodyDown);

					}
				});
				//在顯示的框中寫入默認值對應的text的內容
				var $value=$self.val();
				if($value){
					var $node=self.getNode(options.data,$value);
					if($node){
						$this.val($node.text);
					}
				}
				
				$this.focus(function(){
					if($('#comboDiv').length>0){
						return;
					}
					var $div=$('<div class="panel panel-default combotree" id="comboDiv"><div class="panel-body"><div id="bootstrapCombotree"></div></div></div>');
					$div.appendTo($this.parent());
					$('#bootstrapCombotree').treeview(options);
					var thisObj=$(this);
					var thisOffset=$(this).position();
					var $dialogOffset=thisObj.closest('.modal-dialog').offset();
					var $left=thisOffset.left;
					var $top=thisOffset.top+thisObj.outerHeight();
					$div.css({
						left : $left+"px",
						top: $top+"px",
						zIndex: 1100
					}).slideDown('fast');
					$('body').bind("mousedown",self.onBodyDown);
				});
			};
			if (typeof options == 'string'){
				var method = $.fn.bootstrapCombotree.methods[options];
				if (method){
					return method(this, param);
				}
				return;
			}
			
			options = options || {};
			return this.each(function(){
				var state = $.data(this, 'bootstrapCombotree');
				if (state){
					$.extend(state.options, options);
				} else {
					$options=$.extend({}, $.fn.bootstrapCombotree.defaults, options);
					$options.thisObj=this;
					if($options.url){
						$options.data=getTree($options.url);
					}
					state = $.data(this, 'bootstrapCombotree', {
						options: $options,
					});
				}
				self.create(this);
			});
		}
	});
	
	$.fn.bootstrapCombotree.methods={
		options:function(jq){
			var $option=$.data(jq[0],'bootstrapCombotree').options;
			return $option;
		}
	}
	$.fn.bootstrapCombotree.defaults = {
			expandIcon: "glyphicon glyphicon-plus-sign",
		    collapseIcon: "glyphicon glyphicon-minus-sign",
			emptyIcon:"glyphicon glyphicon-file",
			showBorder:false,
			showTags: true,
			url:'combotree',
			data:[]
		};

})(jQuery)

保存JS中的btnSubmit()方法用於保存數據方法,後臺保存響應方法。

@Override
public Object save(TbMenuForm form) {
    try {
        TbMenu model = new TbMenu();
        Integer id = form.getId();
        if(id != null) {
            model = menuService.findById(id);
        }
        //父級菜單id
        Integer parentId = form.getParentId();
        if(parentId == null) {
            model.setParent(null);
        }else {
            model.setParent(new TbMenu(parentId));
        }
        BeanUtils.copyProperties(form, model,"id", "parent");
        menuService.save(model);
        return new AjaxResult("數據保存成功!");
    } catch (Exception e) {
        return new AjaxResult(false,"數據保存失敗");
    }
}

方法中TbMenuForm接收類,中字段和實體類差不多。代碼如下。

import com.mcy.springbootsecurity.custom.BaseForm;
import com.mcy.springbootsecurity.entity.TbMenu;

public class TbMenuForm {
    private Integer id;
    private String name;
    private String url;
    private Integer idx;
    private TbMenu parent;
    private Integer parentId;

    public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Integer getIdx() {
        return idx;
    }

    public void setIdx(Integer idx) {
        this.idx = idx;
    }

    public TbMenu getParent() {
        return parent;
    }

    public void setParent(TbMenu parent) {
        this.parent = parent;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }
}

AjaxResult爲方法執行完,返回的一個類,這個可以自己隨便返回一個字符串就可以,用於前臺判斷是否保存成功,代碼如下。

import org.springframework.data.domain.Page;
import java.util.HashMap;

/**
 * 方法執行成功後,返回的工具類
 */
public class AjaxResult {
	private Boolean success;
	private String msg;		//提示信息
	
	public Boolean getSuccess() {
		return success;
	}

	public void setSuccess(Boolean success) {
		this.success = success;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	public AjaxResult(String msg) {
		super();
		this.success=true;
		this.msg = msg;
	}
	
	public AjaxResult(Boolean success, String msg) {
		super();
		this.success = success;
		this.msg = msg;
	}

	@SuppressWarnings("rawtypes")
	public static HashMap<String, Object> bulidPageResult(Page page) {
		HashMap<String, Object> result=new HashMap<>();
		result.put("total", page.getTotalElements());
		result.put("rows", page.getContent());
		return result;
	}
	
}

新增和修改效果展示。

最後就剩下刪除了,刪除也是最簡單的。

刪除JS方法代碼。

function btn_delete(){
    var str = $("#menu_table").bootstrapTable('getSelections');
    if(str.length != 1){
        bootbox.alert("請選中一行進行刪除");
    }else{
        bootbox.confirm("確定刪除選中這一行嗎?", function(s){
            if(s){
                var id = str[0].id;
                $.post('menu/delete',{id:id},function(){
                    /* refresh刷新 */
                    $("#menu_table").bootstrapTable('refresh');
                    bootbox.alert('<h4>'+"刪除成功!"+'</h4>');
                });
            }
        });
    }
}

後臺響應請求代碼。

@RequestMapping(value="/delete")
@ResponseBody
public Object delete(Integer id) {
	try {
		menuService.deleteById(id);
		return new AjaxResult("數據刪除成功");
	} catch (Exception e) {
		return new AjaxResult(false,"數據刪除失敗");
	}
}

就這些了,如果對你有幫助,點贊關注一下唄^_^,留下你的足跡。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章