为什么我的Laravel只计算同一页面上的数量,而不是所有选定的项目?

huangapple go评论73阅读模式
英文:

why my laravel only compute the quantity on the same page and not all the selected item?

问题

I have reviewed the code you provided, and it seems like you are working on a Laravel application for an e-commerce-like system. Your main concern appears to be related to how selected items are handled after using the search bar at the top of the page. The selected items are not being computed correctly if they are not on the same page as the search results.

Unfortunately, I cannot see the entire logic of your application, but I can provide some general suggestions to help you debug and potentially solve this issue:

  1. Check Data Loading: Verify that your search functionality is correctly filtering and displaying the search results on the same page. Make sure the search query is being passed to the server, and the server is returning the appropriate data.

  2. Data Pagination: If your system is paginating search results or displaying a limited number of items per page, you should consider how you are handling the selection of items across pages. If a user selects items on one page and then performs a search, you may need to store those selections temporarily (e.g., in a session or JavaScript variable) and reapply them when displaying the search results.

  3. JavaScript Logic: Review your JavaScript code that handles the selection of items and their quantities. Ensure that it correctly identifies the selected items and stores their information, even after a search is performed.

  4. Session Handling: Consider using Laravel's session management to store selected items and quantities. You can store this data in the session when an item is selected and retrieve it when displaying the confirm page.

  5. Debugging: Use debugging tools, such as Laravel's built-in debugging and logging features or browser developer tools, to inspect the data flow and identify where the issue is occurring. Check if the selected items are being passed correctly to the confirm method in your controller after a search.

  6. Test Scenarios: Test different scenarios, such as selecting items on one page, performing a search, and verifying how the selections are handled. Test cases with items on multiple pages to ensure your selection logic works across pages.

Without a more detailed understanding of your application's architecture and the complete code, it's challenging to provide a specific solution. However, the above suggestions should help you troubleshoot and resolve the issue with selected items not being computed correctly after using the search bar.

英文:

selected item before doing the searching

I make an e-commerce like system. the system work fine. but after i use the search bar at the top of the page, and selected the item based on the result of the search, it wont compute the item i selected before i make a search using the search bar.In conclusion, i guess it only counted the selected item if the item are in the same page. here I limit the page length to 200.

result before doing the search

this was successfully computed.

after doing the searching

this is what happen when i use the search bar.

result after doing the search

as you can see, it doent count the previous 2 item.

i will provide the code.

web_item.blade

@extends('frontend.layouts.app')

@section('content')

<link rel="stylesheet" href="{{ asset('css/tablestyle.css') }}" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">

{!! Form::open(['route' => 'frontend.webitem.confirm', 'method' => 'POST']) !!}

{!! Form::submit('Confirm', ['class' => 'btn btn-primary', 'style' => 'float:right;']) !!}
<br>
<table id="webitem-table" class="table table-bordered">
    <thead>
        <tr>
            <th>Part No</th>
            <th>Description</th>
            <th>Supp Part</th>
            <th>RK Qty</th>
            <th>Dealer Price</th>
            <th>Workshop</th>
            <th>End User Price</th>
            <th>Quantity</th>
            <th>Customer Price</th>
            <th>Part Search</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

{!! Form::close() !!}

<script>
    $(document).ready(function () {
        $('#webitem-table').DataTable({
            processing: true,
            ajax: '{!! route('frontend.webitem.webitemtable') !!}',
            columns: [
                {data: 'part_no', name: 'part_no', searchable: true},
                {data: 'description', name: 'description', searchable: true},
                {data: 'supp_part', name: 'supp_part'},
                {data: 'rk_qty', name: 'rk_qty'},
                {data: 'dealer_price', name: 'dealer_price'},
                {data: 'workshop', name: 'workshop'},
                {data: 'enduser_price', name: 'enduser_price'},
                {
                    data: 'quantity', 
                    name: 'quantity', 
                    orderable: false, 
                    searchable: false, 
                    render: function (data, type, row) {
                        return '<input type="number" min="0" name="quantity[' + row.id + ']" value="0">';
                    }
                },
                {
    data: 'user_price',
    name: 'user_price',
    orderable: false,
    searchable: false,
    render: function (data, type, row) {
        return '<input type="number" min="0" step="0.01" name="user_price[' + row.id + ']" value="' + data + '';
    }
                },
                {data: 'part_search', name: 'part_search', visible: false, searchable: true}
            ],
            lengthMenu: [100, 200, 500, 1000], // Add this option to show 200, 500, 1000 and All
            pageLength: 100, // Set default page length to 200
            responsive: true, // Enable responsive design
        });
    });
</script>

@endsection

web_confirm.blade

@extends('frontend.layouts.app')




@section('content')
    <div class="container">
        <h1>Selected Items</h1>

        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Part No</th>
                    <th>Description</th>
                    <th>Supp Part</th>
                    <th>Customer Price</th>
                    <th>Quantity</th>
                    <th>Total Price</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($selectedItems as $selectedItem)
                    <tr>
                        <td>{{ $selectedItem['item']->part_no }}</td>
                        <td>{{ $selectedItem['item']->description }}</td>
                        <td>{{ $selectedItem['item']->supp_part }}</td>
                        <td>{{ $selectedItem['userPrice'] > 0 ? number_format((float) $selectedItem['userPrice'], 2, '.', '') : 'N/A' }}</td>

                        <td>{{ $selectedItem['quantity'] }}</td>
                        <td>{{ number_format((float) $selectedItem['itemTotal'], 2, '.', '') }}</td>
                    </tr>
                @endforeach
            </tbody>
        </table>

        <h2>Total Price: RM {{ $total }}</h2>
        <button type="submit" class="btn btn-primary">Confirm Order</button>
    </div>
@endsection

the is the controller named itemController.php

<?php

namespace App\Http\Controllers\Frontend\webitem;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Access\Webitems;
use App\Models\Access\WebTest;
use Yajra\Datatables\Facades\Datatables;
use App\Models\Order;

class ItemController extends Controller
{
    public function index()
    {
        return view('frontend.webitem.web_item');
    }

    public function webitemtable(Request $request)
    {
        $search = $request->input('search.value'); // Get the search input from DataTables

        $query = Webitems::query();

        // Apply search filters based on 'part_no' and 'description' columns
        if ($search) {
            $query->where('part_no', 'LIKE', "%$search%")
                ->orWhere('description', 'LIKE', "%$search%");
        }

        // Fetch filtered items
        $items = $query->get();

        return Datatables::of($items)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" data-id="' . $item->id . '" name="selected[]" value="' . $item->id . '" data-group="checkbox-group">';
            })
            ->addColumn('action', function ($item) {
                return '<input type="number" min="0" name="quantity[' . $item->id . ']" value="0">';
            })
            ->addColumn('user_price', function ($item) {
                return '<input type="number" min="0" step="0.01" name="user_price[' . $item->id . ']" value="0">';
            })
            
            ->rawColumns(['checkbox', 'action', 'user_price'])
            ->make(true);
    }

   

    public function confirm(Request $request)
    {
        $selectedItems = [];
        $total = 0;

        $items = Webitems::all();

        foreach ($items as $item) {
            $quantity = $request->input('quantity.' . $item->id, 0);
            $userPrice = $request->input('user_price.' . $item->id, 0);

            if ($quantity > 0) {
                $selectedItems[] = [
                    'item' => $item,
                    'quantity' => $quantity,
                    'userPrice' => $userPrice,
                    'itemTotal' => $userPrice * $quantity,
                ];

                $total += $userPrice * $quantity;
            }
        }

        $total = number_format((float) $total, 2, '.', ''); // format the total to 2 decimal places

        return view('frontend.webitem.web_confirm')->with([
            'selectedItems' => $selectedItems,
            'total' => $total,
            'request' => $request,
        ]);
    }
}

this is the route

      Route::group(['prefix' => 'webitem', 'namespace' => 'webitem', 'middleware' => 'auth'], function () {
        Route::get('index', 'ItemController@index')->name('webitem.index');
        Route::get('webitemtable', 'ItemController@webitemtable')->name('webitem.webitemtable');
        Route::get('index_test', 'ItemController@index_test')->name('webitem.index_test');
        Route::get('getDataTable', 'ItemController@getDataTable')->name('webitem.getDataTable');
        Route::post('confirm', 'ItemController@confirm')->name('webitem.confirm');
        
        
        Route::post('/order/confirm', 'ItemController@confirmOrder')->name('order.confirm');

        Route::post('/order/confirm', 'OrderController@confirmOrder')->name('order.confirm');

        Route::post('/submit-order', 'OrderController@submitOrder')->name('submit.order');
        Route::post('/frontend/webitem/process', 'Frontend\webitem\ItemController@confirm')->name('frontend.webitem.process');

on the routes there might be more than needed because ive tried a few things, so just ignore the extra routes and provide with you suggestion

答案1

得分: 0

我认为你需要使用会话来保存所有已选择的项目。因为从你的代码来看,我可以说每次进入已选择项目页面时,它只会反映最新的已选择项目。所以你需要实现“会话”来保留之前的选择。

英文:

I think you have to use session to save all the selected items. Because seeing at your code I can say that every time you go to selected items page it will reflect only latest selected items. So you need to implement Session to retain your previous selections.

huangapple
  • 本文由 发表于 2023年8月9日 16:18:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865831-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定