output orders insert several inputs and send to the controller LARAVEL

0

I need a little help with this, I'm a little new in laravel and js, what I want to achieve is to insert several inputs (products) to an output order (or detail) and send it to the controller. I have the js to insert several records of inputs (that I found in this same site) that works perfectly for me. What I can not do is decode the JSON (since the code has been sent by JSON) to send it to the controller and process it to save it in the database.

I am using this solution but I can not process them in the controller: Create dynamic input with jQuery

 <script type="text/javascript">
  // Refresca Producto: Refresco la Lista de Productos dentro de la Tabla
  // Si es vacia deshabilito el boton guardar para obligar a seleccionar al menos un producto al usuario
  // Sino habilito el boton Guardar para que pueda Guardar
    function RefrescaProducto(){
        var ip = [];
        var i = 0;
        $('#guardar').attr('disabled','disabled'); //Deshabilito el Boton Guardar
        $('.iProduct').each(function(index, element) {
            i++;
            ip.push({ id_pro : $(this).val() });
        });
        // Si la lista de Productos no es vacia Habilito el Boton Guardar
        if (i > 0) {
            $('#guardar').removeAttr('disabled','disabled');
        }
        var ipt=JSON.stringify(ip); //Convierto la Lista de Productos a un JSON para procesarlo en tu controlador
        $('#ListaPro').val(encodeURIComponent(ipt));
    }
       function agregarProducto() {

            var sel = $('#pro_id').find(':selected').val(); //Capturo el Value del Producto
            var text = $('#pro_id').find(':selected').text();//Capturo el Nombre del Producto- Texto dentro del Select


            var sptext = text.split();

            var newtr = '<tr class="item"  data-id="' +sel+'" >';
            newtr = newtr + '<td class="iProduct" >' + text + '</td>';
            newtr = newtr + '<td><input  class="form-control col-sm-1" id="1" name="cantidad" type="text" value="" required /></td>';
            newtr = newtr + '<td><button type="button" class="btn btn-danger btn-xs remove-item"><i class="fa fa-times"></i></button></td></tr>';

            $('#ProSelected').append(newtr); //Agrego el Producto al tbody de la Tabla con el id=ProSelected

            RefrescaProducto();//Refresco Productos

            $('.remove-item').off().click(function(e) {
                $(this).parent('td').parent('tr').remove(); //En accion elimino el Producto de la Tabla
                if ($('#ProSelected tr.item').length == 0)
                    $('#ProSelected .no-item').slideDown(300); 
                RefrescaProducto();
            });        
           $('.iProduct').off().change(function(e) {
                RefrescaProducto();
           });
    }
</script>

  <div class="container col-sm-offset-3 " >
    <h3>Agregar insumos</h3>
    <!-- Trigger the modal with a button -->
    <button type="button" class="btn btn-info" data-toggle="modal" data-target="#myModal">Agregar</button>
      <input type="hidden" id="ListaPro" name="ListaPro" value="" required />

    <table id="TablaPro" class="table col-sm-9" >
        <thead>
            <tr>
                <th>Insumo</th>
                <th>Cantidad</th>

                <th>Acción</th>
            </tr>
        </thead>
        <tbody id="ProSelected"><!--Ingreso un id al tbody-->
            <tr>

            </tr>
        </tbody>
    </table>
    <!-- Modal -->
    <div class="modal fade" id="myModal" role="dialog">

        <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Agregar Insumo a la lista</h4>
                </div>
                <div class="modal-body">
                     <div class="form-group">
                                <label>Insumos</label>
                            <select class="selectpicker form-control" id="pro_id" name="pro_id" data-width='100%' >
                                   @foreach($newinsumos as $newinsumo)
                                    <option value="{{$newinsumo->id}}">{{$newinsumo->nombre}}</option>
                                    @endforeach
                            </select>
            </div>
                </div>
                <div class="modal-footer">
                    <!--Uso la funcion onclick para llamar a la funcion en javascript-->
                    <button type="button" onclick="agregarProducto()" class="btn btn-default" data-dismiss="modal">Agregar</button>
                </div>
            </div>

        </div>
    </div>

driver:

      $data = array();
      foreach($_POST as $key => $value) {  //Recibo el los valores por POST 
        $data[$key] = $value;  
     }

     //dd($data);

      $acturl = urldecode($data['ListaPro']); //decodifico el JSON
      $productos = json_decode($acturl,true);

    foreach ($productos  as $pro) {

         $misProductos = array(
            'cantidad' => $pro->cantidad,
            'insumo_id' => $pro->id_pro,//así llamamos al id del producto en la vista en la funcion RefrescaProducto      
        );
}

print_r ($ products);

Array ( [0] => Array ( [id_pro] => ) )

Error:

ErrorException in OrdenSalidaController.php line 74:
Trying to get property of non-object

dd ($ products);

array:1 [▼
  0 => array:1 [▼
    "id_pro" => ""
  ]
]

dd ($ data);

    array:12 [▼
  "_token" => "htxTHiVFO7totwCWcnYBMjaEArlBsD99prqueEBo"
  "url" => "http://localhost:8888/insumos/desarrollo/public/admin/orden_salidas"
  "id" => "0"
  "page" => "1"
  "fecha_ingreso" => "2018-01-10"
  "responsable" => "Rodrigo Ortiz"
  "establecimiento" => "3"
  "detalle" => "44"
  "_wysihtml5_mode" => "1"
  "ListaPro" => "%5B%7B%22id_pro%22%3A%22%22%7D%2C%7B%22id_pro%22%3A%22%22%7D%5D"
  "cantidad" => "3"
  "pro_id" => "5"
]

pd: if I add more than one input to the output order, it only brings me, as you can see with the dd ($ data) the last input? How can I solve this?

I hope you can help me, try to be as clear as possible. Thank you very much in advance.

    
asked by Jmm kng 10.01.2018 в 15:12
source

1 answer

0

I am not sure I have understood your question, do you want to send the data to the controller in JSON format but are you sent by ajax or is it a POST form? Did you check with a console.log or debugging in javascript the JSON has a correct format? in the controller you use the php variables $ _POST do not know if there is an object Request in laravel that makes it easier to obtain of the data in the calls, with what I see in your code for now I can tell you to check that the JSON in javascript is being sent in the correct format and if you send it through an AJAX, make sure you are passing it dataType: "json" in the options. Greetings

    
answered by 11.01.2018 в 15:39