【问题标题】:Passing parameter to each column of datatable将参数传递给数据表的每一列
【发布时间】:2018-12-05 17:53:18
【问题描述】:

在我的 Laravel 5.6 应用程序中,我尝试将 $id 变量从路由传递到数据表的每一列。

我的代码:

 public function getVendorslistChange($id){
    try {
        return Datatables::of($this->purchaseRepository->getVendorListData(),$id)
            ->addColumn('action', function ($vendor,$id) {
                return \Form::open(['method' => 'POST', 'action' => ['PurchaseController@postChangeVendor',$id], 'class' => 'form']) . '
                <input type="hidden" name="id" value="' . $vendor->id . '" />
                <input type="submit" name="submit" value="Choose" class="btn center-block" />
                ' . \Form::close();
            })
            ->make(true);
    } catch (\Exception $e) {
        return $this->redirectWithErrors($e);
    }
}

这部分$this-&gt;purchaseRepository-&gt;getVendorListData() 将返回以下内容:

public function getVendorListData(){
    $this->vendors = Vendor::Select(
        array(
            'vendors.id',
            'vendors.company_name'
        ))
        ->where('vendors.company_id',return_company_id())
        ->where('status','Active')->get()
    ;
    return $this->vendors;
}

但是有错误说,$id不能传递给addColumn

函数 App\Http\Controllers\PurchaseController::App\Http\Controllers{closure}() 的参数太少,在 /Applications/XAMPP/xamppfiles/htdocs/laravel-project/american_dunnage/vendor/yajra/ 中传递了 1 个laravel-datatables-oracle/src/Utilities/Helper.php 在第 64 行,预计正好是 2

将这样的参数传递给数据表的每一列的正确方法是什么?

【问题讨论】:

    标签: laravel datatable laravel-datatables


    【解决方案1】:

    如果供应商函数不支持,您不应该只向它们添加参数。例如,当您调用Datatables::of() 时,源代码显示它只需要一个参数。所以即使你传递了额外的$id 变量,$id 也不会传递给你给addColumn() 的回调函数。这就是为什么您会看到有关传入的参数太少的错误。

    https://github.com/yajra/laravel-datatables/blob/8.0/src/DataTables.php#L33

    这样的事情可能会奏效。请注意我如何将回调告诉use $id,而不是尝试将其直接传递给函数调用:

    public function getVendorslistChange($id){
        try {
            return Datatables::of($this->purchaseRepository->getVendorListData())
                ->addColumn('action', function ($vendor) use ($id) {
                    return \Form::open(['method' => 'POST', 'action' => ['PurchaseController@postChangeVendor',$id], 'class' => 'form']) . '
                    <input type="hidden" name="id" value="' . $vendor->id . '" />
                    <input type="submit" name="submit" value="Choose" class="btn center-block" />
                    ' . \Form::close();
                })
                ->make(true);
        } catch (\Exception $e) {
            return $this->redirectWithErrors($e);
        }
    }
    

    查看文档中的示例 3,了解如何管理匿名函数范围:

    http://php.net/manual/en/functions.anonymous.php

    【讨论】:

    • 非常感谢。我被这个问题困了一天。
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多