Insert cloned items into the form with PHP and Mysql

Asked

Viewed 110 times

2

Friends, I’m having trouble recording cloned Mysql fields in the form. I’ll try to explain in detail to see if my friends can help me.

<div class="mb-md">
    <a href="#" id="but_add">
        <i class="fa fa-plus text-primary"></i>
        <span class="text-semibold text-primary"> Adicionar Categoria</span>
    </a>
</div>

<div class="categoria row" id="categoria">
<section class="panel panel-border">
<header class="panel-heading">
    <div class="pull-right">
        <a href="#" class="text-primary text-semibold remove-categoria">Excluir</a>
    </div>
    <input type="text" name="ds_categoriacomp[]" class="form-control-small-height" placeholder="Nome" data-plugin-maxlength maxlength="100" required>
    <div class="row col-padding-top-x15">
        <div class="col-md-6">
            <div class="form-group">
                <label class="col-md-1 control-label">Qtd.</label>
                <div class="col-md-8">
                    <div class="input-group">
                        <span class="input-group-addon">min</span>
                        <input type="number" id="qtd_min" name="qtd_min[]" value="0" min="0" max="99" maxlength="2" step="1" required="required" class="form-control-small-height qtd_min"/>
                        <span class="input-group-addon">máx</span>
                        <input type="number" id="qtd_max" name="qtd_max[]" min="1" max="99" maxlength="2" step="1" required="required" class="form-control-small-height"/>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4 pull-right custom-padding-top-x7">
            <div class="checkbox-custom checkbox-default">
                <input type="checkbox" name="cd_obrigatorio[]"/>
                <label>Obrigatório</label>
            </div>
        </div>
    </div>
</header>
<div class="panel-body">
    <div class="row" style="margin-top:-15px;">
    <table class="table mb-none tb-complementos" id="tb-complementos">
        <tr>
            <td class="actions col-sm-2">
            <input id="ds_complemento" name="ds_complemento[]" placeholder="Nome" class="form-control-small-height" data-plugin-maxlength maxlength="100" required>
            </td>
            <td class="actions col-lg-4">
            <input id="ds_descComp" name="ds_desccomp[]" placeholder="Descrição" class="form-control-small-height" data-plugin-maxlength maxlength="2000" required>
            </td>
            <td class="actions text-center col-lg-1">
            <input id="vl_valorcomp" name="vl_valorcomp[]" class="form-control-small-height" placeholder="Preço" onkeyup="formatarMoeda(this);" onChange="carregaPrValor(this.value);" required>
            </td>
            <td class="actions text-center col-lg-1">
                <a href="#" class="remove-complemento">
                    <span class="text-semibold">Excluir</span>
                </a>
            </td>
        </tr>
    </table>
    <a href="#" id="but_add_c" class="but_add_c" style="padding-left:10px;">
        <i class="fa fa-plus text-dark"></i>
        <span class="text-semibold text-dark"> Adicionar complemento</span>
    </a>
</div>
</section>
</div>

The HTML above generates form in the image below: inserir a descrição da imagem aqui

By clicking on Add complement, js function makes a clone of the complement fields as shown below: inserir a descrição da imagem aqui

By clicking on Add category js function generates a clone of the full form, where within this "clone" form I can add more complements and so on. Figure below:

inserir a descrição da imagem aqui

This is where the problem occurs. How can I save in the database since there are two tables, Tabela1 saves the category name and table 2 saves the add-ons.

Below the way I am trying to do in PHP, but without success:

for($i = 0; $i < count($nomecategoria); $i++){
	mysql_query("insert into tabela1 (nomecategoria, valor1, valor2...)values('".$nomecategoria[$i]."', '".$valor1[$i]."', '".$valor2[$i]."')");
	//busca id da categoria gerado no insert
	$idcategoria = mysql_insert_id();
}
for($c = 0; $c < count($nomecomplemento); $c++){
	mysql_query("insert into tabela2 (idcategoria, nomecomplemento, descricao)values('".$idcategoria."', '".$nomecomplemento[$c]."', '".$descricao[$c]."')");
}

The above code saves the categories in the Tabela1 correctly, but when saving the complements in the table 2 the idcategoria is always the same.

Javascript that clones objects:

//add categoria complemento/////////////////////////////////
$(document).ready(function(){
	$('#but_addcategoria').click(function(){
	  var newel = $('.categoria:last')
	  .clone(true)
	  .find("input").val("").end()
	  $(newel).insertAfter(".categoria:last"); 
	 });
});
//add item complemento 
$(document).ready(function(){
	$('#but_addcomplemento').click(function(){
	  var newel = $('.tb-complementos:last')
	  .clone(true)
	  .find("input").val("").end();
	  $(newel).insertBefore(this);
	 });
});

There is an ideal way to make these Inserts so that each add-on gets its own idcategoria correct?

Already thank the friends who try to help.

1 answer

0


The only way I see it is by creating indexes and sub-indices in complement arrays. For example, in the first category form, add-ons would be in sequence:

Complemento 1:
name="ds_complemento[0][0]"
name="ds_desccomp[0][0]"
name="vl_valorcomp[0][0]"

Complemento 2:
name="ds_complemento[0][1]"
name="ds_desccomp[0][1]"
name="vl_valorcomp[0][1]"

And so on. On the second form:

Complemento 1:
name="ds_complemento[1][0]"
name="ds_desccomp[1][0]"
name="vl_valorcomp[1][0]"

Complemento 2:
name="ds_complemento[1][1]"
name="ds_desccomp[1][1]"
name="vl_valorcomp[1][1]"

Note that the first index (the first brackets) follows a sequence of the entire form, where [0] is the first, [1] the second etc. The second bracket is the index of complements linked to the category.

In this case, you would have to do this in the Javascript that clones the elements, so that it correctly sorts the fields with the indexes in the brackets.

With this, PHP will receive the add-ons in a sub, such as:

[ds_categoriacomp] => Array
   (
      [0] => cat 1
      [1] => cat 2
   )
[ds_complemento] => Array
   (
      [0] => Array
         (
            [0] => cat1 comp1
            [1] => cat1 comp2
         )

      [1] => Array
         (
            [0] => cat2 comp1
         )
   )

Note that now each sub-rray index [ds_complemento] is related to a category to a category: index [0] = 1st category, index [1] = 2nd category etc.

With that, your for would look this way, one inside the other, altering the $nomecomplemento for the index of the first for, that is to say, $nomecomplemento[$i]:

for($i = 0; $i < count($nomecategoria); $i++){
    mysql_query("insert into tabela1 (nomecategoria, valor1, valor2...)values('".$nomecategoria[$i]."', '".$valor1[$i]."', '".$valor2[$i]."')");
    //busca id da categoria gerado no insert
    $idcategoria = mysql_insert_id();
   for($c = 0; $c < count($nomecomplemento[$i]); $c++){
      mysql_query("insert into tabela2 (idcategoria, nomecomplemento, descricao)values('".$idcategoria."', '".$nomecomplemento[$c]."', '".$descricao[$c]."')");
   }
}

Cloning the elements

Create a function that will be called every time you clone or delete elements. This function will change the attributes name complements by creating ordered sub-indices linked to the indices of the categories:

function subIndices(){
   var cats = $(".categoria");
   cats.each(function(idx){
      var tabs = $(this).find(".tb-complementos");
      var cidx = idx;
      tabs.each(function(idx){
         $(this).find("[name^='ds_complemento']").attr("name", "ds_complemento["+cidx+"]["+idx+"]");
         $(this).find("[name^='ds_desccomp']").attr("name", "ds_desccomp["+cidx+"]["+idx+"]");
         $(this).find("[name^='vl_valorcomp']").attr("name", "vl_valorcomp["+cidx+"]["+idx+"]");
      });
   });
}

You will call this function at the end of all events that clone or delete elements, such as:

$(document).ready(function(){
    $('#but_addcomplemento').click(function(){
      var newel = $('.tb-complementos:last')
      .clone(true)
      .find("input").val("").end();
      $(newel).insertBefore(this);
      subIndices(); // CHAMA A FUNÇÃO
     });
});

Like I said, put subIndices(); at the end of all events.

  • Thanks for the answer Sam. My js cloning the object is quite simple, I added the code at the end of the question. Would you have any tips on how to create indexes and subindexes in add-ons arrays? !

  • I’ll try to do it here and warn you.

  • I updated the answer.

  • Thank you very much Sam, I will test and then inform here the result.

  • Sam, now it was right the idcategory of each complement, however the values ds_complement, ds_desccomp and vl_valorcomp, save in the base a string Array. No for do PHP did as you said. Strange pq the other fields save correctly.

  • Well, that’s something. Let’s go after the problem with the array now.

  • Yes, it’s enough. The way I was doing was very wrong.

  • I think the $nomecomplemento[$c] and the $descricao[$c] should have the sub-index: $nomecomplemento[$i][$c] and $descricao[$i][$c]

  • Okay, it worked perfectly, that’s exactly it, the sub-index was missing in the variables. Thank you very much Sam, solved my problem I’ve been hitting for days.

Show 4 more comments

Browser other questions tagged

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