列表树组件/ztree
1、视图文件:
PHP Code复制内容到剪贴板
- <?= \backend\widgets\grid\TreeGrid::widget([
- 'dataProvider' => $dataProvider,
- 'keyColumnName' => 'department_id',
- 'parentColumnName' => 'parent',
- 'parentRootValue' => null, //first parentId value
- 'pluginOptions' => [
- 'initialState' => 'expanded',// expanded默认展开,collapse收起,只显示一级栏目
- ],
- 'columns' => [
- 'department_name',
- 'level',
- 'myorder',
- [
- 'class' => 'yii\grid\ActionColumn',
- 'template' => '{create} {view} {update} {delete}',
- 'buttons' => [
- 'create' => function ($url, $model) {
- return Html::a("<i class='fa fa-plus'></i>", ['create', 'id' => $model->department_id], ['class' => 'btn btn-default btn-xs']);
- }
- ]
- ],
- ],
- ]); ?>
2、如果使用searchModel,数据不要分页:
PHP Code复制内容到剪贴板
- 'pagination' => false, //不分页
PHP Code复制内容到剪贴板
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- ...,
- [['parent_id'], 'checkParent'],
- ];
- }
- /**
- * 检测父级是否存在并且赋值level
- * @param $attribute
- * @param $params
- */
- public function checkParent($attribute, $params)
- {
- $parent_id = $this->$attribute;
- if ($parent_id) {
- $parent = self::findOne($parent_id);
- if ($parent) {
- // 如果有父级,节点层级加1
- $this->level = ($parent->level += 1);
- } else {
- $this->addError($attribute, '父级节点不存在');
- }
- }
- }
- /**
- * 递归删除子分类
- */
- public function afterDelete()
- {
- $ids = $this->getChildrenIds($this->id);
- self::deleteAll(["in", "id", $ids]);
- parent::afterDelete();
- }
- /**
- * 获取指定父级下的所有子级ID
- * @param $categoryId
- * @return array
- */
- public function getChildrenIds($categoryId)
- {
- $ids = [];
- $res = self::find()->where(["parent_id" => $categoryId])->all();
- if ($res) {
- foreach ($res as $val) {
- $ids[] = $val['id'];
- $ids = array_merge($ids, $this->getChildrenIds($val['id']));
- }
- }
- return $ids;
- }
- /**
- * 获取下拉树列表
- *
- * @param string $id
- * @return array
- */
- public static function getDropDownTreeList($id = '')
- {
- $list = self::find()
- ->andFilterWhere(['<>', 'id', $id])
- ->select(['id', 'parent_id', 'title'])
- ->orderBy('sort asc,id asc')
- ->asArray()
- ->all();
- $tree = Tree::build($list,'id', 'parent_id', 'children', 0);
- return self::generationDropDown($tree);
- }
- /**
- * 生成下拉选择的列表结束
- * @param array $tree
- * @param array $result
- * @param int $deep
- * @param string $separator
- * @return array
- */
- protected static function generationDropDown($tree = [], &$result = [], $deep = 0, $separator = '--'){
- $deep++;
- foreach ($tree as $list) {
- $result[$list['id']] = str_repeat($separator, $deep - 1) . $list['title'];
- if (isset($list['children'])) {
- self::generationDropDown($list['children'], $result, $deep);
- }
- }
- return $result;
- }
参照【用户管理】 - 【部门管理】
checkbox 组件
use backend\widgets\ztree\CheckboxWidget;
PHP Code复制内容到剪贴板
- <?= $form->field($module, 'ttids')->widget(CheckboxWidget::className(), [
- 'nodes' => \backend\models\InfoType::getDropdownZtree($module->ttids),
- 'options' => [
- 'level' => 0, // (可选)默认为0不限,允许选择的checkbox的树级别
- 'selectAll' => true, //(可选)默认为true,是否显示全选/取消全选按钮
- ],
- ])->label(false); ?>
PHP Code复制内容到剪贴板
- <?= \backend\widgets\ztree\CheckboxWidget::widget(
- [
- 'name' => 'select-menu',
- 'nodes' => \backend\modules\user\models\Permission::getTreeData(),
- 'options' => [
- 'value' => ''
- ]
- ]
- ) ?>
这里的nodes需要遵循格式为:
[
{
"id":1,
"pId":0,
"checked":false
}
]
添加点击回调事件:
PHP Code复制内容到剪贴板
- <?= \backend\widgets\ztree\CheckboxWidget::widget(
- [
- 'name' => 'select-menu',
- 'nodes' => $treeData,
- 'options' => [
- 'id' => 'select-rbac-menu',
- 'value' => ''
- ],
- 'setting' => [
- 'callback' => '{onCheck : onCheckRole}', // 点击回调
- ]
- ]
- ) ?>
JavaScript Code复制内容到剪贴板
- <script>
- var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
- var selectNodes = null;
- /**
- * 点击节点的回调事件
- * @param event
- * @param treeId 对应 zTree 的 treeId
- * @param treeNode 被点击的节点 JSON 数据对象
- * @param clickFlag 节点被点击后的选中操作类型,可忽略
- */
- function onCheckRole(event, treeId, treeNode, clickFlag) {
- var treeObj = $.fn.zTree.getZTreeObj("select-rbac-menu");
- var nodes = treeObj.getCheckedNodes(true);
- var ids = [];
- for (var i = 0; i < nodes.length; i++) {
- ids.push(nodes[i].origin);
- // ids[] = nodes[i].origin
- }
- selectNodes = ids;
- // console.log(ids);
- }
- </script>
model方法:
PHP Code复制内容到剪贴板
- /**
- * 获取分类下拉树列表
- * @param $defaultIds
- * @return array
- */
- public static function getDropdownZtree($defaultIds)
- {
- if($defaultIds){
- $defaultIds = explode(",",$defaultIds);
- }
- $ret = []; //返回的数据
- $res = self::find()->orderBy("myorder asc,typeid desc")->all();
- foreach ($res as $k => $p){
- if(!$p){
- continue;
- }
- $arr = [
- "id" => $p->typeid,
- "pId" => '0',
- "name" => $p->tname,
- ];
- if ($defaultIds) {
- if (in_array($p->typeid, $defaultIds)) {
- $arr['checked'] = true;
- }
- }
- $ret[] = $arr;
- }
- // p($ret);
- return $ret;
- }
树列表:
PHP Code复制内容到剪贴板
- <?= \backend\widgets\ztree\DefaultNodesWidget::widget(
- [
- 'name' => 'status-manage',
- 'nodes' => \backend\models\StatusManage::getDropDownStatusType(),
- 'search' => false,
- 'setting' => [
- 'callback' => '{onClick : clickStatusMenu}', // 点击回调
- ]
- ]
- ) ?>
如果写原生就不必放到页面最下面
PHP Code复制内容到剪贴板
- <script>
- /**
- * 点击节点的回调事件
- * @param event
- * @param treeId 对应 zTree 的 treeId
- * @param treeNode 被点击的节点 JSON 数据对象
- * @param clickFlag 节点被点击后的选中操作类型,可忽略
- */
- function clickStatusMenu(event, treeId, treeNode, clickFlag) {
- // console.log(treeNode);
- // console.log(treeNode.id);
- layer.load(2, {time: 1 * 1000}); //又换了种风格,并且设定最长等待1秒
- // 更新刷新页面,并在reload时给服务器传参数
- var url = "<?=\yii\helpers\Url::to(["index"])?>" + "&type=" + treeNode.id;
- // 更新页面
- console.log(url);
- // return false;
- window.location.href = url;
- // $.pjax({url: url, container: '#countries', timeout: 0});
- }
- </script>
PHP Code复制内容到剪贴板
- /**
- * 获取状态类型可选择的树型列表
- * @return array
- */
- public static function getDropDownStatusType(){
- $res = self::find()->where(["type"=>0])->orderBy("myorder asc,status desc")->asArray()->all();//默认0是状态类型
- $list = [];
- $list[] = [
- "id" => "0_0",
- "pId" => 0,
- "name" => "状态类型",
- "open" => true,
- ];
- foreach ($res as $k => $v){
- $list[] = [
- "id" => $v["status"],
- "pId" => $v["parent_status"]?$v["parent_status"]:"0_0",
- "name" => $v["name"],
- "open" => true,
- ];
- }
- return $list;
- }