Laravel Backpack如何获取筛选后的集合?按钮点击返回全量集合
问题解决方法
核心原因
页面筛选条件通过GET参数传递给列表页,但按钮表单是POST提交,未携带当前筛选参数;同时Backpack的$this->crud->query在自定义POST方法中不会自动应用筛选逻辑,导致获取全量数据。
步骤1:修改按钮视图,携带筛选参数
在表单中添加隐藏字段,将当前页面的所有筛选参数(搜索、列筛选等)一并提交:
<form action="{{ url($crud->route.'/withdrawAllCompanyDebt') }}" method="POST"> {{-- 传递当前所有筛选参数,兼容数组类型参数 --}} @foreach(request()->query() as $key => $value) @if(is_array($value)) @foreach($value as $item) <input type="hidden" name="{{ $key }}[]" value="{{ $item }}"> @endforeach @else <input type="hidden" name="{{ $key }}" value="{{ $value }}"> @endif @endforeach <button class="btn btn-warning" data-style="zoom-in"> <span class="ladda-label"> {{ trans('columns.debt.allwithdraw') }} </span> </button> {{ csrf_field() }} </form>
这段代码会自动把URL上的GET参数转为表单隐藏字段,支持多选筛选等数组类型参数。
步骤2:修改后台处理方法,应用筛选逻辑
在自定义方法中手动触发Backpack的列表筛选逻辑,确保查询应用提交的筛选参数:
use Illuminate\Http\Request; public function withdrawDebtCompany(Request $request) { // 初始化列表操作配置,加载筛选规则 $this->crud->setupListOperation(); // 将POST提交的筛选参数合并到Crud请求中 $this->crud->request->merge($request->all()); // 执行筛选逻辑,更新查询条件 $this->crud->applyFilters(); // 此时获取的是筛选后的集合 $bills = $this->crud->query->get(); // 后续业务逻辑保持不变 Bill::tryWithdrawalsIncrement($bills); $res['success'] = 0; $res['err'] = 0; $bills->each(function($bill) use(&$res){ $paym = new PaymentsController(); $result = $paym->payDebt(new Request([ 'bill_id'=>$bill->id, ])); if($result['code'] == 0) { $res['success'] += 1; } else { $res['err'] += 1; } }); \Alert::add('warning', 'Успешно списано: '.$res['success'].' | Неуспешно списано: '. $res['err'])->flash(); return redirect()->back(); }
特殊场景处理(AJAX无刷新筛选)
如果筛选是AJAX动态加载(无页面刷新),页面URL不会更新筛选参数,需用JS获取Datatables当前查询参数,动态添加到表单:
document.querySelector('.btn-warning').addEventListener('click', function(e) { const table = $('#crudTable').DataTable(); const queryParams = table.settings()[0].ajax.data(); // 清空已有的隐藏参数 document.querySelectorAll('[name^="filter_"]').forEach(el => el.remove()); // 动态添加筛选参数 for (const key in queryParams) { const input = document.createElement('input'); input.type = 'hidden'; input.name = key; input.value = queryParams[key]; this.form.appendChild(input); } });
内容的提问来源于stack exchange,提问作者stadia_raspada
相关产品推荐
相关产品推荐

