直接上案例演示,情景分析,我这里有一个文章,后台需要调用文章栏目下拉框使用.文章栏目存在多级.
我看到这个多级下拉功能,在权限管理,角色组中,有这个功能,通过分析,把代码抄过来了..
首先,我们在common模块中的ArticleCategory模型中,写一个查询所有栏目的方法.
项目\application\common\model\ArticleCategory.php
/**
* 返回文章栏目列表
* @return array|false|\PDOStatement|string|\think\Collection
*/
public function getArticleCategoryLists()
{
$result=[];
$list=$this->where(["status"=>1])->order("id","asc")->field(["id","pid","name"])->select();
$result=$list;
return $result;
}
随后,在后台控制器的初始化函数中,把这个数据,给拼装一下,项目\application\admin\controller\Articles.php
public function _initialize()
{
parent::_initialize();
$this->model = new \app\common\model\Articles;
$ArticleCategory=new ArticleCategory();
$articleCategoryLists = $ArticleCategory->getArticleCategoryLists();
Tree::instance()->init($articleCategoryLists);
$result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
$categoryLists=[];
foreach ($result as $k => $v) {
$categoryLists[$v['id']] = $v['name'];
}
$this->view->assign('categoryLists', $categoryLists);
}
这里调用了fastadmin自带的用了Tree方法,把一个二维数组,拼接成(id=>名称)的一维数组,这样在前端通过控件,直接调用.
use fast\Tree;
新增
{:build_select('row[pid]', $categoryLists, 0, ['class'=>'form-control selectpicker', 'data-rule'=>'required'])}
修改
{:build_select('row[pid]', $categoryLists, $row['pid'], ['class'=>'form-control selectpicker', 'data-rule'=>'required'])}
实现效果
来源:oschina
链接:https://my.oschina.net/laobia/blog/3156457