如何使用Ajax在laravel中保存多个行表单?

时间:2018-10-23 05:39:14

标签: php jquery ajax laravel

嘿,我对此有些困惑。如何使用Ajax在Laravel 5.5中输入多行表单?这个想法是添加项目,添加项目时,项目编号会递增,然后 我想将此表保存在数据库中: enter image description here

这是我的刀片服务器代码及其脚本:

pr-items.blade.php

@extends('layouts.app')
@section('content')

<div class="container-fluid">
<!-- Your main wrapper -->

    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-heading"><h3 class="panel-title">Add Items</h3></div>
                <div class="panel-body">

                    <form name="add_item" id="add_item" class="form-inline">
                    {{ csrf_field() }}


                      <div class="form-group">
                        <label for="pr_form_number">PR Form Number: </label>
                        <input type="text" class="form-control" name="pr_number" value="{{$pr_details}}" readonly required><br><br>
                      </div>

                      <div class="table-responsive">
                        <table class='table table-bordered table-hover' id="tab_logic">
                            <thead>
                                <tr class='info'>
                                    <th style='width:10%;'>ITEM NO.</th>
                                    <th style='width:10%;'>QTY</th>
                                    <th style='width:10%;'>UNIT</th>
                                    <th style='width:30%;'>DESCRIPTION</th>
                                    <th style='width:10%;'>COST PER UNIT</th>
                                    <th style='width:10%;'>COST PER ITEM</th>
                                    <th style='width:10%;'>ACTION</th>
                                </tr>
                            </thead>
                            <thead>
                                <tr id="addr0">
                                    <td class="custom-tbl"><input class='form-control input-sm'style='width:100%;' type="text" value="1" id="pr_item0" name="pr_item[]" readonly required></td>
                                    <td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_qty0" oninput='multiply(0);' name="pr_qty[]"></td>
                                    <td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_unit0" name="pr_unit[]"></td>
                                    <td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_desc0" name="pr_desc[]"></td>
                                    <td><input class='form-control input-sm' style='width:100%;' type="text" id="pr_cpu0" oninput='multiply(0);' name="pr_cpu[]"></td>
                                    <td class="custom-tbl"><input class='estimated_cost form-control input-sm' id="pr_cpi0" style='width:100%;' type="text" name="pr_cpi[]" readonly></td>
                                    <td class="custom-tbl"><button type="button" id="add" class="btn btn-info btn-sm"><span class="glyphicon glyphicon-plus"></span></button></td>
                                </tr>
                            </thead>
                            <tbody id="dynamic_field">

                            <tbody>
                            <tfoot>
                                <tr class='info'>
                                    <td style='width:65%;text-align:right;padding:4px;' colspan='5'>GRAND TOTAL:</td>
                                    <td style='padding:0px;'>

                                            <input style='width:100%;' type='text' class='form-control input-sm' id='grand_total' name='grand_total' value='0' readonly required>

                                    </td>

                            </tfoot>

                        </table>
                      </div>


                      <button type="button" id="submit" name="submit" class="btn btn-default">Submit</button>
                    </form>

                </div>

            </div>
        </div>

    </div>


</div>



@endsection

@section('script')
<script type="text/javascript">



$(document).ready(function(){      
      var postURL = "<?php echo url('addmore'); ?>";
      var i=1;  


      $('#add').click(function(){
           i++;  
           $('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td class="custom-tbl"><input id="pr_item'+i+'" class="form-control input-sm"style="width:100%;" type="text" value="'+i+'" name="pr_item[]" readonly required></td><td class="custom-tbl"><input id="pr_qty'+i+'"class="form-control input-sm" style="width:100%;" type="text" oninput="multiply('+i+');" name="pr_qty[]"></td><td class="custom-tbl"><input id="pr_unit'+i+'"class="form-control input-sm" style="width:100%;" type="text" name="pr_unit[]"></td><td class="custom-tbl"><input id="pr_desc'+i+'" class="form-control input-sm" style="width:100%;" type="text" name="pr_desc[]"></td><td class="custom-tbl"><input id="pr_cpu'+i+'" class="form-control input-sm" style="width:100%;" type="text" oninput="multiply('+i+');" name="pr_cpu[]"></td><td class="custom-tbl"><input id="pr_cpi'+i+'" class="estimated_cost form-control input-sm" style="width:100%;" type="text" name="pr_cpi[]" readonly></td><td class="custom-tbl"><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn-sm btn_remove"><span class="glyphicon glyphicon-remove"></span></button></td></tr>');  
      });  


      $(document).on('click', '.btn_remove', function(){  
           var button_id = $(this).attr("id");   
           $('#row'+button_id+'').remove();  
      });

      $.ajaxSetup({
          headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });


      $('#submit').click(function(){            
           $.ajax({  
                url:"{{route('pr.items.add')}}",  
                method:"POST",  
                data:$('#add_item').serialize(),
                type:'json',

           });  
      });  

    });




</script>

<script type="text/javascript">
    function multiply(id)
        {
            var total1=parseFloat($('#pr_qty'+id).val())*parseFloat($('#pr_cpu'+id).val());
            $("input[id=pr_cpi" + id + "]").val(total1);
            grandTotal();
        }
function grandTotal()
        {
            var items = document.getElementsByClassName("estimated_cost");
            var itemCount = items.length;
            var total = 0;
            for(var i = 0; i < itemCount; i++)
            {
                total = total +  parseFloat(items[i].value);
            }
            document.getElementById('grand_total').value = total;
        }
</script>

@endsection

这是我的控制器的一部分,用于存储其数据

PurchaseRequestItemController.php

 public function store(Request $request)
    {
        //


        $rules = [];


        foreach($request->input('pr_item') as $key => $value) {
            $rules["pr_item.{$key}"] = 'required';
            $rules["pr_qty.{$key}"] = 'required';
            $rules["pr_unit.{$key}"] = 'required';
            $rules["pr_desc.{$key}"] = 'required';
            $rules["pr_cpu.{$key}"] = 'required';
            $rules["pr_cpi.{$key}"] = 'required';
        }


        $validator = Validator::make($request->all(), $rules);


        if ($validator->passes()) {


            foreach($request->input('pr_item') as $key => $value) {

                $Record=new PurchaseRequestItemModel;

                $Record->pr_form_number = $request->get('pr_number');
                $Record->item_no = $request->get('pr_item');
                $Record->pr_qty = $request->get('pr_qty');
                $Record->pr_unit = $request->get('pr_unit');
                $Record->pr_description =$request->get('pr_desc') ; 
                $Record->pr_cost_per_unit =$request->get('pr_cpu') ;
                $Record->pr_estimated_cost =$request->get('pr_cpi') ;

                $Record->save();
            }


            return response()->json(['success'=>'done']);
        }else{

        return response()->json(['error'=>$validator->errors()->all()]);}




    }

编辑:而且我的表单是一个数组。 我还如何确保保存后可以按原样查看表?

保存时也会返回此错误 enter image description here

4 个答案:

答案 0 :(得分:2)

使用此

$pr_item=$request->get('pr_item');
$pr_qty=$request->get('pr_qty');
$pr_unit=$request->get('pr_unit');
$pr_desc=$request->get('pr_desc');
$pr_cpu=$request->get('pr_cpu');
$pr_cpi=$request->get('pr_cpi');
for($i = 0; $i < count($request->get('pr_item')); $i++)
            $Record=new PurchaseRequestItemModel;
            $Record->pr_form_number =    $request->get('pr_number');
            $Record->item_no =           $pr_item[$i];
            $Record->pr_qty =            $pr_qty[$i];
            $Record->pr_unit =           $pr_unit[$i];
            $Record->pr_description =    $pr_desc[$i]; 
            $Record->pr_cost_per_unit =  $pr_cpu[$i];
            $Record->pr_estimated_cost = $pr_cpi[$i];
            $Record->save();
        }

答案 1 :(得分:2)

例如$ request-> get('pr_number');这是一个数组,因此如果不定义索引就无法获取特定值。您必须定义数组的索引。尝试这个。希望它能工作。

foreach($request->input('pr_item') as $key => $value) {

            $Record=new PurchaseRequestItemModel;

            $Record->pr_form_number = $request->get('pr_number')[$key];
            $Record->item_no = $request->get('pr_item')[$key];
            $Record->pr_qty = $request->get('pr_qty')[$key];
            $Record->pr_unit = $request->get('pr_unit')[$key];
            $Record->pr_description =$request->get('pr_desc')[$key]; 
            $Record->pr_cost_per_unit =$request->get('pr_cpu')[$key];
            $Record->pr_estimated_cost =$request->get('pr_cpi')[$key];

            $Record->save();
        }

答案 2 :(得分:1)

 Use $request->all() and fetch values as below it will work.

 foreach( $request->all() as $value ) {
    $record = new PurchaseRequestItemModel;
    $record->pr_form_number = $value['pr_number'];
    $record->item_no = $value['pr_item'];
    $record->pr_qty = $value['pr_qty'];
    $record->pr_unit = $value['pr_unit'];
    $record->pr_description =$value['pr_desc')];
    $record->pr_cost_per_unit =$value['pr_cpu')];
    $record->pr_estimated_cost =$value['pr_cpi')];
    $record->save();
}

答案 3 :(得分:0)

希望这对您有帮助

foreach($request->input('pr_item') as $key => $value) 
{
     $item = new PurchaseRequestItemModel;
     $item ->pr_form_number = $request->get('pr_number')[$key];
     $item ->item_no = $request->get('pr_item')[$key];
     // mention other fields here
     $item ->save();
}