Skip to content

基础使用

简单示例

php

namespace app\admin\controller;
use app\model\Testorder;
use app\model\User;
use Encore\Admin\Grid;
use Encore\Admin\Form;
use Encore\Admin\Show;
use Encore\Admin\Url;
use Illuminate\Support\Collection;
use LinAdmin\controller\CNewController;

class Ctestorder extends CNewController
{
    protected $header = '测试表格';
    protected $model = Testorder::class;

    /**
     * 数据列表
     * @return Grid
     */
    public function table()
    {
        $table = new Grid(new $this->model());
        // 关联用户表,指定查询字段
        $table->model()->with('user', "nickname,avatar");
        $table->column("id", "ID");
        $table->column('user_id', '用户ID');
        $table->column('user.nickname', '用户昵称');
        $table->column('user.avatar', '头像')->image();
        $table->column("create_time", "创建时间")->date();
        $table->actions(function (Grid\Displayers\Actions $action) {
            $action->enableShow(); // 启用详情查看,默认关闭
        });
        // 导出 CSV 文件
        $table->export(function (Grid\Exporters\CsvExporter $export) {
            $export->filename("测试表格明细"); // 文件名,导出时自动追加时间戳
            $export->except(["avatar"]); // 排除不需要导出的字段
        });
        $table->filter(function (Grid\Filter $filter) {
            $filter->disableIdFilter();
            $filter->like('user.nickname',"用户昵称");
        });


        return $table;
    }
}

基本使用方法

添加列(column)

php
// 添加单列
$table->column('username', '用户名');

// 添加多列
$table->columns('email', 'username' ...);

自定义列显示内容(display)

php
$table->column('email')->display(function ($email) {
    return "mailto:$email";
});

// 添加数据库中不存在的虚拟字段列
$table->column('column_not_in_table')->display(function () {
    return 'blablabla....'.$this->id;
});

获取当前行数据(row)

php
$table->column('first_name');
$table->column('last_name');

// 通过虚拟字段组合当前行的多列数据
$table->column('full_name')->display(function () {
    return $this->first_name.' '.$this->last_name;
});

创建按钮(createButton)

php
// 隐藏创建按钮
$table->disableCreateButton();
// 显示创建按钮
$table->showCreateButton();

查询过滤器(filter)

php
// 隐藏过滤器
$table->disableFilter();
// 显示过滤器
$table->showFilter();

批量操作按钮(batchActions)

php
// 隐藏批量操作按钮
$table->disableBatchActions();
// 显示批量操作按钮
$table->showBatchActions();

// 隐藏批量删除按钮
$table->disableBatchDelete();
// 显示批量删除按钮
$table->showBatchDelete();

刷新按钮(refresh)

php
// 隐藏刷新按钮
$table->disableRefreshButton();
// 显示刷新按钮(默认显示)
$table->showRefreshButton();

整个工具栏(allTools)

php
// 隐藏全部工具栏
$table->disableAllTools();
// 显示全部工具栏
$table->showAllTools();

设置表格宽度

默认宽度为 100%,不会出现横向滚动条。

php
$table->setTableWidth("150%");
$table->setTableWidth("1500px");

显示列字段的总和(totalRow)

php
$table->column('money', '金额')->totalRow(function ($total) {
    return "$".$total;
});

隐藏行选择框

php
$table->disableRowSelector();

字段帮助提示(help)

php
$table->column("sort", "排序")->help("数值越小越靠前")->number();