How to take data from a dynamic HTML table to register?

Asked

Viewed 1,069 times

0

I have the following situation:


I’m trying to log the data from Protocol checklist, but this data is inside a dynamic HTML table, as shown in the following image:

inserir a descrição da imagem aqui

When trying to save this data, only the last record (item 4) is passed in the request (request variable). Note the image below the variable debug "dd($request)"; which only displayed the last data from the Protocol Checklist table.

inserir a descrição da imagem aqui

My question is how to save all data from the modal Checklist Protocol in the checklist_protocol table of the database? Follows the ER model of the database: inserir a descrição da imagem aqui



Error:

The following error occurred while trying to save Checklist data protocol: Call to Undefined method Symfony Component Httpfoundation Parameterbag::save()

inserir a descrição da imagem aqui The codes responsible for implementing this functionality will be presented.


Modal Checklist page protocol edits.blade.php:

  <!--Inicio do modal de Checklist do Projeto-->
<form id="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 taking the view data and taking it to the controller. I’m not sure if it’s correct, because I couldn’t debug the data variable.

 $(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;


});



Registration methodChecklistProtocolo of the Project Controller. 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 file.php:

$this->group(['middleware' => ['auth'], 'namespace' =>'admin','prefix'=>'projetos'], function(){ 
$this->post('cadastroCheckProtocolo','ProjetoController@cadastroChecklistProtocolo')->name('projeto.cadastroCheckProtocolo');
}
  • On the line where a console.log(data) is returning the data correctly?

1 answer

1

When you mount the HTML responsible for the table. You should put a [] in front of the name and use the tag form 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 you submit the form and dump into $_POST or $_GET depending on what you’re using. You’ll 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 the data that will be sent processData: false. and data : data.

Option 2:

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

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

I hope something said here helps you somehow.

See you around.

  • Hello, I did the following test in the interaction loop, I switched the foreach by the for. As the following code shows:

  • for ($i = 0; $i < sizeof($checklistProtocolo); $i++) <tr> <td><input type="text" class="form-control" id="{$checklistProtocolo[$i]->item}}" name="{$checklistProtocolo[$i]->item}}" value="{$checklistProtocolo->item}}" size ="2"></td> </tr> endfor

  • But the following error occurred: Cannot use Object of type stdClass as array (View: C: xampp htdocs Union Resources views admin project edits.blade.php)

  • No need to exchange for for for foreach. It could look the same. Just add the [] in front of the name. Like this. <td><input type="text" class="form-control" id="observacao" name="observacao[]" value="{{$checklistProtocolo->observacao}}" size ="1" style="width: 300px; height: 60px"></td>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.