如何添加选择下拉过滤器

问题描述 投票:0回答:1

问题或功能请求摘要

我正在尝试添加 3 个过滤器(状态、发件人、收件人)。我如何使用

Yajra\DataTables\Services\DataTable
类来做到这一点?

问题代码片段

<?php

namespace App\DataTables\Payments;

use App\Models\Order;
use App\Models\Payment;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Services\DataTable;

class BankTransferDataTable extends DataTable
{
    protected $exportColumns = [
        'id', 'order_id', 'order_number', 'invoice_number', 'bulk_order_key',
        'add_on', 'email', 'mobile_number', 'g_bank', 'bank_name', 'account_name',
        'account_number', 'payment_date', 'amount', 'deposit_slip', 'status',
        'transaction_id', 'created_at', 'updated_at', 'phone', 'order_status', 'order_total'
    ];

    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            // ->filter(function ($query) {
            //  if (request()->has('search')) {
            //      $query->where(function($query) {
            //          $query->where('categories.name', 'LIKE', '%' . request('search')['value'] . '%')
            //          ->orWhere('categories.slug', 'LIKE', '%' . request('search')['value'] . '%');
            //      }); 
            //  }
            // })
            ->addColumn('Order #', function ($payment) {
                return $payment->bulk_order_key;
            })
            ->addColumn('Gifted Account', function ($payment) {
                return $payment->g_bank;
            })
            ->addColumn('Bank Name', function ($payment) {
                return $payment->bank_name;
            })
            ->addColumn('Account Name', function ($payment) {
                return $payment->account_name;
            })
            ->addColumn('Status', function ($payment) {
                if ($payment->transaction_id) {
                    return $payment->get_wallet_transaction_status();
                } else if($payment->bulk_order_key) {
                    $orderStatus = Order::select(['status'])
                        ->where('bulk_order_key', $payment->bulk_order_key)
                        ->first();

                    if ($orderStatus) {
                        return $orderStatus->status;
                    }
                }

                return $payment->order_status;
            });
            // ->addColumn('Actions', function ($category) {
            //  return view('backend.catalog.categories.action', compact('category'));
            // });
    }

    /**
     * Get query source of dataTable.
     *
     * @param  \App\Payment  $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(Payment $model)
    {
        $filters = request()->has('search.value') && filled(request('search.value')) ? json_decode(request('search.value'), true)['filters'] : [];

        return $model->newQuery()
            ->selectRaw('payments.*, orders.phone, orders.status as order_status, orders.total as order_total')
            ->leftJoin('orders', 'payments.order_id', '=', 'orders.id')
            ->whereRaw('payments.bulk_order_key <> ""');

            if (filled($filters['status'])) {
                $query->where('payments.status', $filters['status']);
            }

            $query->when((request()->has('from') && request()->has('to')), function ($query) {
                $query->whereDate('payments.created_at', '>=', request()->get('from'));
                $query->whereDate('payments.created_at', '<=', request()->get('to'));
            })
            ->when((request()->has('from')), function ($query) {
                $query->whereDate('payments.created_at', '>=', request()->get('from'));
                $query->whereDate('payments.created_at', '<=', date('Y-m-d', strtotime('today')));
            })
            ->when((request()->has('to')), function ($query) {
                $query->whereDate('payments.created_at', '>=', date('Y-m-d', strtotime('-5 years')));
                $query->whereDate('payments.created_at', '<=', request()->get('to'));
            })
            ->orderBy('payments.created_at', 'desc');
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
            ->setTableId('bankTransferPaymentsTable')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->dom('Brtip')
            ->orderBy(1)
            ->buttons(
                Button::make('export')->buttons(['csv']),
                Button::make('reset')
                    ->text('<span><i class="fa fa-undo"></i> Refresh</span>'),
            );
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            Column::make('Order #'),
            Column::make('Gifted Account'),
            Column::make('Bank Name'),
            Column::make('Status'),
            // Column::make('Actions')
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'bank_transfer_payments_report_' . date('YmdHis');
    }
}

还有风景:

{{ $dataTable->scripts() }}
<script>
    $(function () {
        const filter = () => {
            const filters = {
                filters: {
                    status: $('#filterStatus').val()
                }
            };

            // window.LaravelDataTables["bankTransferPaymentsTable"].destroy();

            window.LaravelDataTables["bankTransferPaymentsTable"].search(JSON.stringify(filters)).draw();
                
            $('#bankTransferPaymentsTable').DataTable().ajax.reload();
        };

        $(document).on('change', '#filterStatus', function() {
            filter();
        });
    });
</script>

过滤截图

enter image description here

问题

从下拉列表中选择状态时,表数据不会刷新/重新加载。我也没有从控制台得到任何输出。

系统详情

  • 操作系统:MacOS
  • PHP 版本:8.1
  • Laravel 版本:8.83.27
  • Laravel-数据表版本:9.11
jquery laravel datatables yajra-datatable
1个回答
0
投票

似乎您的代码中有一个

return
语句阻止您的代码(在返回之后)被执行:

public function query(Payment $model)
    {
        $filters = request()->has('search.value') && filled(request('search.value')) ? json_decode(request('search.value'), true)['filters'] : [];

        return $model->newQuery() //Change this here and it should be solved :)
            ->selectRaw('payments.*, orders.phone, orders.status as order_status, orders.total as order_total')
            ->leftJoin('orders', 'payments.order_id', '=', 'orders.id')
            ->whereRaw('payments.bulk_order_key <> ""');

           //... rest of code
    }

© www.soinside.com 2019 - 2024. All rights reserved.