数据表格事件

初始化

通过 Grid::resolving 方法可以监听表格初始化事件。

开发者可以在这两个事件中改变 Grid 的一些设置或行为,比如需要禁用掉某些操作,可以在 app/Admin/bootstrap.php 加入下面的代码:

  1. use Dcat\Admin\Grid;
  2. Grid::resolving(function (Grid $grid) {
  3. $grid->disableActions();
  4. $grid->disablePagination();
  5. $grid->disableCreateButton();
  6. $grid->disableFilter();
  7. $grid->disableRowSelector();
  8. $grid->disableTools();
  9. $grid->disableExport();
  10. });
  11. // 只需要监听一次
  12. Grid::resolving(function (Grid $grid) {
  13. ...
  14. }, true);

这样就不用在每一个控制器的代码中来设置了。

如果全局设置后,要在其中某一个表格中开启设置,比如开启显示操作列,在对应的实例上调用 $grid->disableActions(false); 就可以了

构建

通过 Grid::composing 方法可以监听表格被调用事件。

  1. Grid::composing(function (Grid $grid) {
  2. ...
  3. });
  4. // 只需要监听一次
  5. Grid::composing(function (Grid $grid) {
  6. ...
  7. }, true);

fetching回调

通过 Grid::fetching 方法可以监听表格获取数据之前事件,此事件在 composing 事件之后触发。

  1. $grid = new Grid(...);
  2. $grid->fetching(function () {
  3. ...
  4. });
  5. // 可以在 composing 事件中使用
  6. Grid::composing(function (Grid $grid) {
  7. $grid->fetching(function (Grid $grid) {
  8. ...
  9. });
  10. });

rows回调

通过 Grid::rows 方法可以监听表格获取数据之后事件。

  1. use Dcat\Admin\Grid\Row;
  2. use Illuminate\Support\Collection;
  3. $grid->rows(function (Collection $rows) {
  4. /**
  5. * 获取第一行数据
  6. *
  7. * @var Row $firstRow
  8. */
  9. $firstRow = $rows->first();
  10. if ($firstRow) {
  11. // 获取第一行的 id
  12. $id = $firstRow->id;
  13. // 转化为数组
  14. $row = $firstRow->toArray();
  15. }
  16. });

collection回调

这个方法和display回调不同的是,它可以批量修改数据, 参考下面实例中的几个使用场景:

  1. use Illuminate\Support\Collection;
  2. $grid->model()->collection(function (Collection $collection) {
  3. // 1. 可以给每一列加字段,类似上面display回调的作用
  4. $collection->transform(function ($item) {
  5. $item['full_name'] = $item['first_name'] . ' ' . $item['last_name'];
  6. return $item;
  7. });
  8. // 2. 给表格加一个序号列
  9. $collection->transform(function ($item, $index) {
  10. $item['number'] = $index;
  11. return $item;
  12. });
  13. // 3. 从外部接口获取数据填充到模型集合中
  14. $ids = $collection->pluck('id');
  15. $data = getDataFromApi($ids);
  16. $collection->transform(function ($item, $index) use ($data) {
  17. $item['column_name'] = $data[$index];
  18. return $item;
  19. });
  20. // 最后一定要返回集合对象
  21. return $collection;
  22. });

$collection表示当前这一个表格数据的模型集合, 你可以根据你的需要来读取或者修改它的数据。