【问题标题】:How to generate fixed dynamic input fields based on product_id count in Laravel如何在 Laravel 中根据 product_id 计数生成固定的动态输入字段
【发布时间】:2020-09-01 08:03:36
【问题描述】:

我正在使用 Laravel-5.8 向发票添加动态输入字段。我已经写了这段代码:

产品型号:

class Product extends Model
{
   protected $fillable = [
              'id',
              'is_published', 
              'name',
            ];
  public function invoice(){
    return $this->belongsToMany('App\Invoice');
 }
}

发票型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    protected $fillable = [
              'id',
              'customer_id',
              'product_id',
              'invoice_date',
              'qty',
              'price',
          ];
    public function customer(){
        return $this->belongsTo('App\Customer');
    }
    public function product(){
        return $this->belongsToMany('App\Product');
    }
}

每张发票都有一种或多种产品。

发票控制器

控制器

public function create()
{
  $product_count = Product::where('is_published',0)->count();
  $customers = Customer::all();
  $products = Product::all();
  return view('invoice.create', compact('customers','products'));
}

public function store(Request $request)
{
$request->validate([
    'customer_id' => 'required',
    'product_id' => 'required',
    'qty' => 'required',
    'price' => 'required',
    'dis' => 'required',
    'amount' => 'required',
]);
$product_count = Product::where('is_published',0)->count();
$invoice = new Invoice();
$invoice->customer_id = $request->customer_id;
$invoice->total = 1000;
$invoice->save();
foreach ( $request->product_id as $key => $product_id){
    $sale = new Product();
    $sale->qty = $request->qty[$key];
    $sale->price = $request->price[$key];
    $sale->dis = $request->dis[$key];
    $sale->amount = $request->amount[$key];
    $sale->product_id = $request->product_id[$key];
    $sale->invoice_id = $invoice->id;
    $sale->save();
 }
 return redirect('invoice/'.$invoice->id)->with('message','invoice created Successfully');
}

查看

    <form  method="POST" action="{{route('invoice.store')}}">
@csrf
   <div class="form-group col-md-3">
     <label class="control-label">Customer Name</label>
     <select name="customer_id" class="form-control">
     <option>Select Customer</option>
     @foreach($customers as $customer)
          <option name="customer_id" value="{{$customer->id}}">{{$customer->name}} </option>
     @endforeach
     </select>                            
  </div>
  <div class="form-group col-md-3">
     <label class="control-label">Date</label>
     <input name="date"  class="form-control datepicker"  value="<?php echo date('Y-m-d')?>" type="date" placeholder="Enter your email">
  </div>

  <table class="table table-bordered">
    <thead>
       <tr>
           <th scope="col">Product Name</th>
           <th scope="col">Qty</th>
           <th scope="col">Price</th>
           <th scope="col">Discount</th>
           <th scope="col">Amount</th>
           <th scope="col"><a class="addRow"><i class="fa fa-plus"></i></a></th>
         </tr>
       </thead>
       <tbody>
           <tr>
             <td><select name="product_id[]" class="form-control productname" >
                <option>Select Product</option>
              @foreach($products as $product)
                   <option name="product_id[]" value="{{$product->id}}">{{$product->name}}</option>
              @endforeach
                     </select></td>
            <td><input type="text" name="qty[]" class="form-control qty" ></td>
            <td><input type="text" name="price[]" class="form-control price" ></td>
            <td><input type="text" name="dis[]" class="form-control dis" ></td>
           <td><input type="text" name="amount[]" class="form-control amount" ></td>
           <td><a   class="btn btn-danger remove"> <i class="fa fa-remove"></i></a></td>
         </tr>
       </tbody>
       <tfoot>
        <tr>
         <td></td>
         <td></td>
         <td></td>
         <td><b>Total</b></td>
         <td><b class="total"></b></td>
         <td></td>
        </tr>
       </tfoot>

    </table>
    <div >
       <button class="btn btn-primary" type="submit">Submit</button>
    </div>
</form>

javascipt

<script type="text/javascript">
    $(document).ready(function(){
        $('tbody').delegate('.productname', 'change', function () {
            var  tr = $(this).parent().parent();
            tr.find('.qty').focus();
        })
        $('tbody').delegate('.productname', 'change', function () {
            var tr =$(this).parent().parent();
            var id = tr.find('.productname').val();
            var dataId = {'id':id};
            $.ajax({
                type    : 'GET',
                url     :'{!! URL::route('findPrice') !!}',
                dataType: 'json',
                data: {"_token": $('meta[name="csrf-token"]').attr('content'), 'id':id},
                success:function (data) {
                    tr.find('.price').val(data.sales_price);
                }
            });
        });
        $('tbody').delegate('.qty,.price,.dis', 'keyup', function () {
            var tr = $(this).parent().parent();
            var qty = tr.find('.qty').val();
            var price = tr.find('.price').val();
            var dis = tr.find('.dis').val();
            var amount = (qty * price)-(qty * price * dis)/100;
            tr.find('.amount').val(amount);
            total();
        });
        function total(){
            var total = 0;
            $('.amount').each(function (i,e) {
                var amount =$(this).val()-0;
                total += amount;
            })
            $('.total').html(total);
        }
        $('.addRow').on('click', function () {
            addRow();
        });
        function addRow() {
            var addRow = '<tr>\n' +
                '         <td><select name="product_id[]" class="form-control productname " >\n' +
                '         <option value="0" selected="true" disabled="true">Select Product</option>\n' +
'                                        @foreach($products as $product)\n' +
'                                            <option value="{{$product->id}}">{{$product->name}}</option>\n' +
'                                        @endforeach\n' +
                '               </select></td>\n' +
'                                <td><input type="text" name="qty[]" class="form-control qty" ></td>\n' +
'                                <td><input type="text" name="price[]" class="form-control price" ></td>\n' +
'                                <td><input type="text" name="dis[]" class="form-control dis" ></td>\n' +
'                                <td><input type="text" name="amount[]" class="form-control amount" ></td>\n' +
'                                <td><a   class="btn btn-danger remove"> <i class="fa fa-remove"></i></a></td>\n' +
'                             </tr>';
            $('tbody').append(addRow);
        };
        $('.remove').live('click', function () {
            var l =$('tbody tr').length;
            if(l==1){
                alert('you cant delete last one')
            }else{
                $(this).parent().parent().remove();
            }
        });
    });
</script>

从下图看:

Product_id, qty, price 是数组。 我希望生成的动态字段的行数基于 Product 中 product_id 的计数。例如,如果数据库中只有五 (5) 个产品,它应该在视图刀片中自动生成五行 Product_id、qty、price 字段。

如何修改我的控制器并查看刀片代码以实现此目的?

我的意思是如何使视图刀片中的 addRow 等于 $product_count。也就是说,我想计算产品表中的记录/行。这将确定要生成的动态行。

谢谢

【问题讨论】:

  • 所以你想让 ?
  • @AlzafanChristian - 不。我的意思是,如图所示,如果只有 3 个产品,那么生成的字段数将为 3。如果我们有七 (7) 个产品,则为 7字段将自动生成,无需按添加按钮。谢谢

标签: jquery laravel


【解决方案1】:

根据评论,如果这是你想要达到的,你可以试试这个:

<tbody>
  @for($x=0;$x<$product_count();$x++)//auto generate x rows limit from $product_count, remove if dont need this
  <tr>
    <td>
      <select name="product_id[]" class="form-control productname" >
        <option>Select Product</option>
        @foreach($products as $product)
          <option name="product_id[]" value="{{$product->id}}">{{$product->name}}</option>
        @endforeach
      </select>
    </td>
    <td><input type="text" name="qty[]" class="form-control qty" ></td>
    <td><input type="text" name="price[]" class="form-control price" ></td>
    <td><input type="text" name="dis[]" class="form-control dis" ></td>
    <td><input type="text" name="amount[]" class="form-control amount" ></td>
    <td><a class="btn btn-danger remove"> <i class="fa fa-remove"></i></a></td>
  </tr>
  @endfor
</tbody>

在javascript中,我只是将.remove行上的逻辑复制到.addRow

$('.addRow').on('click', function () {
  var count = $('tbody tr').length;
  if(count >= {{$product_count}}){ //max row as defined in $product_count
    alert('your alert')
   }else{
     addRow();
   }
});

【讨论】:

  • 在我的控制器中我有: $product_count = Product::where('is_published',0)->count();我的意思是如何使视图刀片中的 addRow 等于 $product_count
  • 有点让我在“不按添加按钮自动生成(总产品)”和这个之间感到困惑。如果要限制总行数,请将 $product_count 作为 javascript 变量传递,以设置 addRow() 中从数据表计数的行数限制
  • 对此我感到非常抱歉。我想计算产品表中的记录/行。这将确定要生成的动态行。谢谢
  • 请用详细信息更新问题(例如产品是否已发布等),我明天会尽力帮助您,现在是深夜,我需要睡觉xD
  • 试试修改我的答案,把$products->count()换成$product_count,看看是不是你想要的。
猜你喜欢
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
相关资源
最近更新 更多