dcat admin 本身提供的模型树 ,可以实现拖拽排序的功能,只是这个功能没办法融合现有的数据表格相关的功能,所以网上找了一个支持拖拽的插件 :https://github.com/pstldz/dcat-admin-grid-sotrable 。官方本身也提供了一个支持拖拽的插件,不过是基于 1.0 的,我们的项目版本 2.2 没办法使用。
插件的安装
安装
1
| composer require pstldz/dcat-admin-grid-sotrable
|
然后打开http://yourhost/admin/auth/extensions
,依次点击 更新
和 启用
。
使用
修改模型
1 2 3 4 5 6 7 8 9 10 11 12
| use Spatie\EloquentSortable\Sortable; use Spatie\EloquentSortable\SortableTrait;
class Template extends Model implements Sortable { use SortableTrait;
public $sortable = [ 'order_column_name' => 'order_column', 'sort_when_creating' => true, ]; }
|
添加数据仓库
1 2 3 4 5 6 7 8 9
| <?php
use Dcat\Admin\Repositories\EloquentRepository; use App\Entities\Template as TemplateModel;
class Template extends EloquentRepository { protected $eloquentClass = TemplateModel::class; }
|
在表格中使用对应的排序字段
1 2 3 4 5
| use App\Repositories\Template;
return Grid::make(Template::class, function (Grid $grid) { $grid->sortable('order_column'); };
|
定制逻辑
由于这个插件默认是按照排序字段正序的,项目中使用的是倒序,且要把已隐藏的模板置后,所以自定义了排序逻辑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Template extends Model implements Sortable { use SortableTrait;
public $sortable = [ 'order_column_name' => 'order_column', 'sort_when_creating' => true, ];
public function scopeOrdered(Builder $query, string $direction = 'desc') {
return $query->orderByDesc('status') ->orderByDesc('sort') ->orderByDesc('id'); } }
|
修改了排序逻辑之后,需要修改保存排序按钮的工具逻辑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <?php
namespace Pstldz\DcatAdminGridSotrable;
use Dcat\Admin\Admin; use Dcat\Admin\Form; use Dcat\Admin\Grid\Tools\AbstractTool; use Illuminate\Http\Request;
class SaveOrderButton extends AbstractTool { public function handle(Request $request) { $status = true; $column = $request->post('_column'); $message = admin_trans('sortable.save_succeeded'); $repository = $request->post('_model');
$sorts = $request->post('_sort'); $sorts = collect($sorts) ->pluck('key') ->combine( collect($sorts)->pluck('sort')->sortDesc() # 改成倒序 ); }
|