Dcat Admin框架不支持表格规格筛选器的默认选中,所以这边实现的思路使用过JS实现默认选中,通过获取url中的参数,如果筛选字段不存在则通过js获取相应节点,进行默认选中。
<?php
namespace App\Admin\Controllers;
use App\Admin\Repositories\Selector;
use App\Common\Enums\CategoryEnum;
use Dcat\Admin\Admin;
use Dcat\Admin\Grid;
class SelectorController extends AdminController
{
/**
* Make a grid builder.
* @return Grid
*/
protected function grid() {
// 设置默认选中
$params = request()->get('_selector');
$isType = $params['type'] ?? -1;
$isCate = $params['cate'] ?? -1;
Admin::script(
<<<JS
var isType = $isType
var isCate = $isCate
setSelect()
function setSelect() {
if (isCate == -1) {
$('.grid-selector .wrap:nth-child(1) li:first a:first').addClass('active')
}
if (isType == -1) {
$('.grid-selector .wrap:nth-child(2) li:first a:first').addClass('active')
}
}
JS
);
return Grid::make(new Selector(), function (Grid $grid) {
if (request()->get('_view_') !== 'list') {
// 设置自定义视图
$grid->view('admin.rank.download');
}
$grid->paginate(50);
$grid->column('url', '图片')->image('', 100);
$grid->selector(function (Grid\Tools\Selector $selector) {
$selector->selectOne('cate', '分类', [0 => '小米', 1 => '华为', 7 => 'OPPO', 30 =>'VIVO']);
$selector->selectOne('type', '日期', [0 => '今天', 1 => '昨天', 7 => '近一周', 30 =>'近一月']);
});
// 禁掉筛选按钮
$grid->disableFilterButton();
// 禁用操作按钮
$grid->disableActions();
// 设置边线
$grid->withBorder();
// 设置复选框
$grid->disableRowSelector();
$grid->disableCreateButton();
$grid->disableRefreshButton();
});
}
}
备注:如果有多个筛选项,则通过修改.wrap:nth-child(1) 中的值,依次设置默认选中的字段,如果筛选项过多可以将上面JS封装下,不用每个分类都写一遍。