laravel-admin 添加、编辑按钮支持携带参数
xuexi 2025-11-18 10:40:40 发表在:PHP 查看数:20
通过修改源码实现laravel-admin添加、编辑按钮支持携带参数,解决一些特殊功能需求,并且不影响之前添加和编辑程序运行。

自定义添加方法

打开vendor\encore\laravel-admin\src\Gird.php
//public $tableID下增加变量
public $queryString="";
修改方法 getCreateUrl()
public function getCreateUrl()
    {
        $queryString = '';

        if ($constraints = $this->model()->getConstraints()) {
            $queryString = http_build_query($constraints);
        }

        return sprintf(
            '%s/create%s',
            $this->resource(),
            $queryString ? ('?'.$queryString) : ''
        );
    }
改为
public function getCreateUrl()
    {
        $queryString = $this->queryString;
        if ($constraints = $this->model()->getConstraints()) {
            $queryString = http_build_query($constraints);
        }

        return sprintf(
            '%s/create%s',
            $this->resource(),
            $queryString ? ('?'.$queryString) : ''
        );
    }
表格调用
$grid->queryString='village=10&id=1';

自定义编辑方法.表格方法修改

在列表中加入
use App\Admin\Actions\Tag\edit;

$grid->actions(function ($actions) {
            $actions->disableedit();
            $actions->add(new edit);
        });
app\Admin\Actions\Tag 文件夹下新增edit.php
<?php

namespace App\Admin\Actions\Tag;

use Encore\Admin\Actions\RowAction;

class edit extends RowAction
{
    public $name = '更改';

    /**
     * @return  string
     */
    public function href()
    {
        $tag_type=request('tag_type');  
        return "{$this->getResource()}/{$this->getKey()}/edit?type=".$tag_type[0];
    }
}

注意,这个传值要保持一致,要有值,不然会报错

Trying to access array offset on null (View: /www/wwwroot/jg.oaos.net/laravel/vendor/encore/laravel-admin/resources/views/grid/actions/dropdown.blade.php)

感谢作者,转载自https://blog.csdn.net/weixin_39616995/article/details/134263274

我还修改了下这个问题,可以保证参数为空的时候不报错

 public function href()
{
    $tag_type = request('changjia_id');  

    // 处理空值情况:为空或非数组时不拼接参数
    if (empty($tag_type) || !is_array($tag_type)) {
        return "{$this->getResource()}/{$this->getKey()}/edit";
    }

    // 参数有效时拼接第一个元素
    return "{$this->getResource()}/{$this->getKey()}/edit?changjia_id=" . $tag_type[0];
}
最近访问时间:2025-11-19 06:01:26
知识库:397条鸣谢:TAY  备案号:蜀ICP备2024090044号-1