How to get data from a dynamic HTML table to make a record?

0

I have the following situation:

I'm trying to register data from the Protocol Checklist , but this data is inside an HTML PivotTable, as shown in the following image:

Whentryingtosavethisdata,onlythelastrecord(item4)ispassedintherequest(variablerequest).Noticetheimagebelowthedebugofthe"dd ($ request)" variable; which only displayed the last data in the Protocol Checklist table.

MyquestionishowtosavealldatafromthemodalChecklistProtocolinthechecklist_protocoltableofthedatabase?Here'sthedatabaseERmodel:


Error:

  

Thefollowingerroroccurredwhiletryingtosavethechecklistdata  protocol:Calltoundefinedmethod  Symfony\Component\HttpFoundation\ParameterBag::save()

Thecodesresponsibleforrunningthisfunctionalitywillbepresented.

Modalchecklistprotocoledita.blade.php:

<!--IniciodomodaldeChecklistdoProjeto--><formid="checklistProtocolo" action="{{route('projeto.cadastroCheckProtocolo')}}" method="POST">

                     {{ csrf_field() }} 
  <div class="modal fade modal-default" id="modalChecklist" aria-hidden="true" aria-labelledby="examplePositionCenter"
                 role="dialog" tabindex="-1">
                <div class="modal-dialog2 modal-center">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                            <h4 class="modal-title">Checklists do Protocolo</h4>
                        </div>

                        <div class="form-group col-md-4">
                             <input type="hidden" id="projeto_id" name="projeto_id" value="{{$projeto->id}}">
                             <input type="hidden" id="modelo_id"  name="modelo_id" value="{{$modeloProtocolo[0]['id']}}">
                             <label class="control-label">Modelo</label>
                             <input type="text" class="form-control" name="modeloProcesso" value="{{$modeloProtocolo[0]['modelo']}}" disabled> 

                        </div>
                        <div class="modal-body">
                        <div class="form-group col-md-18">

                             <table id="checklistProtocolo" name="checklistProtocolo" class="table table-hover table-striped table-responsive toggle-arrow-tiny" >
                                <caption></caption>
                                    <thead>
                                        <tr>
                                            <th>Item</th> 
                                            <th>Descrição</th>
                                            <th>Sim/Não</th>
                                            <th>Não Atende</th>
                                            <th>Data de Validade</th>
                                            <th>Página do Documento</th>
                                            <th><center>Observações</center> </th>
                                            <th class="text-center"></th>
                                        </tr>
                                    </thead>
                                    <tbody id="bodyChecklists">



                                @foreach($checklistsProtocolos as $checklistProtocolo)

                                <tr>
                                    <td><input type="text" class="form-control"  id="item" name="item" value="{{$checklistProtocolo->item}}"  size ="2"></td>
                                    <td>{{$checklistProtocolo->descricao_item}}</td>   
                                         <input type="hidden"     id="item_descricao_id"  name="item_descricao_id" value="{{$checklistProtocolo->item_descricao_id}}">
                                    <td><input type="checkbox"    id="sim_nao"            name="sim_nao" {{$checklistProtocolo->sim_nao == null ? '' : 'checked'}}></td>
                                    <td><input type="checkbox"    id="nao_atende"         name="nao_atende" {{$checklistProtocolo->nao_atende == null ? '' : 'checked'}} ></td>
                                    <td><input type="date"       class="form-control" id="dt_validade"      name="dt_validade" value="{{$checklistProtocolo->dt_validade}}"></td>
                                    <td><input type="text"       class="form-control" id="pagina_documento" name="pagina_documento" value="{{$checklistProtocolo->pagina_documento}}" size ="1"></td>
                                    <td><input type="text"       class="form-control" id="observacao"       name="observacao" value="{{$checklistProtocolo->observacao}}" size ="1" style="width: 300px; height: 60px"></td>
                                </tr>

                            @endforeach  



                               </tbody>
                        </table>



                        </div>

                        </div><!--Fim do modal-body-->

                        <div class="modal-footer">
                        <center>
                        <button type="submit" class="btn btn-primary"  aria-hidden="true" style="width: 300px; height: 40px" > Salvar</button>
                           <!--  <a id="btnSalvarChecklistProtocolo" type="button" class="btn btn-primary cadChecklistProtocolo" 
                            data-dismiss="modal"  align="center" style="width: 300px; height: 40px">Salvar</a> -->
                        </center>
                        </div>
                    </div>
                </div>
            </div>
            </form>  
  <!--Fim do modal do Checklist do Projeto-->  



JavaScript file responsible for grabbing data from the view and taking it to the controller. I'm not sure if it's correct because I could not debug the variable data.

 $(document).on('click', '#btnSalvarChecklistProtocolo', function () {

});

//Ajax para o cadastro do checklists do protocolo
$('.cadChecklistProtocolo').click(function () {

  var dados  =  [];
  var i     =  0;

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


  var table = $('#checklistProtocolo');
  table.find('tr').each(function () {
     dados[i]['item']  =  $( this ).find( 'td:nth-child(1)' ).text();
     dados[i]['item_descricao_id']  =  $( this ).find( 'td:nth-child(2)' ).val();
     dados[i]['sim_nao']  =  $( this ).find( 'td:nth-child(3)' ).val();
     dados[i]['nao_atende']  =  $( this ).find( 'td:nth-child(4)' ).val();
     dados[i]['dt_validade']  =  $( this ).find( 'td:nth-child(5)' ).val();
     dados[i]['pagina_documento']  =  $( this ).find( 'td:nth-child(6)' ).text();
     dados[i]['observacao']  =  $( this ).find( 'td:nth-child(7)' ).text();
     i++;
  });

  console.log(dados)


  $.ajax({
      url: "/projetos/cadastroCheckProtocolo",
      type: "POST",
      data: {meusDados:dados},
      dataType: "json"
  }).done(function (response) {
      console.log(response);
      if (response.success) {    

       setTimeout(() => {

          alert ('Sucesso ao Cadastrar o Checklist de Protocolos');
            window.location.reload();
        }, 500);
      }
      else {
        alert("Erro ao Cadastrar o Checklist de Protocolos");
      }   
  }).fail(function (response) {

        alert ("Erro ao Cadastrar o Checklist de Protocolos");
  });
  return false;


});



ProjectControllerProtocolProtocol Method This method is responsible for registering the protocol checklist data.

 public function cadastroChecklistProtocolo(Request $request)
        {

           //Deletar a tabela de checklist_protocolo
           $checklistsProtocolos = ChecklistProtocolo::where('projeto_id','=', $request->projeto_id)->delete();



           //Recebe os dados do modal Checklist Protocolo
            $checklistProtocolo =  $request->request;

            $checklistProtocolo->save();//está ocorrendo um problema no momento de salvar os dados

        }


Route, web.php file:

$this->group(['middleware' => ['auth'], 'namespace' =>'admin','prefix'=>'projetos'], function(){ 
$this->post('cadastroCheckProtocolo','ProjetoController@cadastroChecklistProtocolo')->name('projeto.cadastroCheckProtocolo');
}
    
asked by anonymous 19.11.2018 / 15:26

1 answer

1

When you mount the HTML responsible for the table. You should put a [] in front of the name and use the form tag as well instead of mounting the request data manually.

Example:

<input type="text" name="nome[]" id="nome_1" value="Matheus">
<input type="text" name="nome[]" id="nome_2" value="Ruama">

When sending the form and dump in $ _POST or $ _GET depending on what you are using. You will see.

Array(
    "nome" => Array (
        (string) Matheus
        (string) Ruama
    )
)

Option 1:

To continue, you can then select the Form with Jquery and pass it to a var data = new FormData($("seletor do form aqui")[0]) ;

In ajax add this option to tell jquery not to process data that will be sent processData: false. and data : data .

Option 2:

Still considering that you created the form and changed the way it mounts your HTML. Select the form with jquery and slave var data = $("seletor do form aqui").serialize() .

In this option nothing in the submission (part of ajax) will need changes.

I hope something here said will help you in some way.

See you later.

    
19.11.2018 / 18:58