fastadmin下拉框筛选使用方法
在列表使用:
无论在哪里使用,都需要先关联对应的模型。所以,需要先修改模型文件:application/admin/model/Project.php
public function company()
{
return $this->belongsTo(Company::class, 'company_id', 'id', [], 'left')->setEagerlyType(0);
}
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id', [], 'left')->setEagerlyType(0);
}
然后需要修改控制器代码:application/admin/controller/Project.php
protected $model = null;
protected $searchFields = ['id', 'title', 'contact'];
protected $relationSearch = true;
....
/**
* 查看
*/
public function index()
{
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->where($where)
->with(['user' => function ($query) {
$query->withField('username,nickname,mobile,id_card');
}, 'company' => function ($query) {
$query->withField('name');
}])
->order($sort, $order)
->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
修改后台列表对应的js文件:public/assets/js/backend/project.js
{
field: 'user_id',
title: '发布用户',
formatter: function (value, row) {
return row.user.nickname || row.user.username || '';
},
addclass: 'selectpage',
extend: 'data-source="user/user/index" data-field="nickname" data-format-item="{nickname}(ID:{id})"'
},
{
field: 'company_id',
title: '公司名称',
formatter: function (value, row) {
return row.company.name || '';
},
addclass: 'selectpage',
extend: 'data-source="company/index"'
},
这样修改后,就可以在列表筛选这个下拉数据了。
在编辑和添加页面使用
添加:application/admin/view/project/add.html
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Project_id')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-project_id" data-rule="required" min="0" data-source="project/index" class="form-control selectpage" name="row[project_id]" type="text" value="">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('User_id')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-user_id" data-rule="required" min="0" data-source="user/user/index" data-field="nickname" class="form-control selectpage" name="row[user_id]" type="text" value="">
</div>
</div>
编辑页面一样,就无需介绍了。