save dynamic form data

2

Good morning, I hope you can help me resolve this question because I am new to this. I am developing a form to generate surveys dynamically, in the form you can add questions, each question can be added an indefinite number of options as shown in the following image.

Each input parent (question), has child fields (options) that are also added dynamically, so I had to add a variable to assign numbering to the parent fields (questions), since that way I can tell Each child to which group of questions belongs, but when adding an option to a second question always added it in the first one in the same way when removing questions or a specific option.

My question is: how to print the data of that dynamic form in another sheet.php I try with foreach and for and it does not work for me, since I need to save the information in a BD.

I have the code in the following way:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Calendario</title>
  <link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
  <link rel="stylesheet" href="../css/bootstrap-datetimepicker.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <script type="text/javascript" src="nuevo.js"></script>
</head>
<style type="text/css">
  .col-md-12.fieldwrapper {
    margin-bottom: 2%;
  }

  .valor {
    width: 20%;
    float: left;
  }

  .opcion {
    width: 50%;
    float: left;
  }

  .fieldname {
    width: 85%;
    display: inline;
  }

  .cuerpo {
    background: #fff;
    padding: 5%;
    box-shadow: 10px 0px 5px 0px rgba(0, 0, 0, 0.47);
  }
  /*  .new{
                  margin-left: 1.5%;
                }*/

  .remove {
    margin-left: 1%;
  }

  .subfield .remove {
    margin-top: 1%;
  }

  .btn-success {
    background: #00541c;
    border-color: #00541c;
  }

  .subfield {
    margin-top: 1%;
  }
</style>

<body style="background:#d6d6d6;">


  <script type="text/javascript">
    //script para agregar los formulario dinamicos  en el div que tiene la id llamada buildyourform cada vez que le da clic en el boton que tiene como  id add
    $(document).ready(function() {
      $("#add").click(function() {

        //agrega el primer gripo de la pregunta
        var intId = $("#buildyourform  div").length + 1;
        var fieldWrapper = $("<div  class = \"form-group\" class =\"col-md-10 fieldwrapper\" role=\"list\" id=\"field" + intId + "\"/>");
        var fName = $("<input type=\"text\" name = \" pregunta" + intId + "\" class=\"fieldname form-control\" placeholder=\" Preguna\" required />");
        var subWrapper = $("<fieldset id=\"subwrapper" + intId + "\"/>");

        var newButton = $("<button type=\"button\" class=\"new btn btn-success btn-sm\" id=\"new" + intId + "\"><span class=\"glyphicon glyphicon-plus\"></span></button");
        newButton.click(function() {

          //grupo para las opiones
          var Id = $("#subwrapper" + intId + " aside").length + 1;

          var subfield = $("<aside class =\"col-md-12 subfield\" id=\"subfield" + Id + "\"/>");
          var Name = $("<input type=\"text\" name =\"opcion" + Id + "" + intId + "\" class=\"opcion form-control\" placeholder=\" Opción\" required />");
          var value = $("<input type=\"number\" name = \"valor" + Id + "" + intId + "\" class=\"valor form-control\" placeholder=\" Valor\"  required />");

          //elimina una opcion espesifica
          var removeButton1 = $("<button type=\"button\" class=\"remove btn btn-danger btn-sm\"><span class=\"glyphicon glyphicon-trash\"></span></button");

          removeButton1.click(function() {
            $(this).parent().remove();
          });

          subfield.append(Name);
          subfield.append(value);
          subfield.append(removeButton1);
          subfield.append(subdato);

          $("#subwrapper" + intId).append(subfield);

        });

        //elimina una pregunta espesifica
        var removeButton = $("<button type=\"button\" id=\"remove\" class=\"remove btn btn-danger btn-sm\"><span class=\"glyphicon glyphicon-trash\"></span></button");
        removeButton.click(function() {
          $(this).parent().remove();
        });

        fieldWrapper.append(fName);
        fieldWrapper.append(newButton);
        fieldWrapper.append(removeButton);
        fieldWrapper.append(subWrapper);
        fieldWrapper.append(dato);

        $("#buildyourform").append(fieldWrapper);
      });


      $(".remove").click(function() {

        //alert("hola");
        $(this).parent().remove();

      });

    });
  </script>

  <div class="content">
    <div class="col-md-10 cuerpo">
      <center>
        <h3>Nueva encuesta</h3>
      </center>
      <form class="form-horizontal" method="post" action="guardaEncuesta.php" target="_blank">
        <div class="form-group col-md-12" role="listitem">

          <input type="text" name="titulo" class="form-control" placeholder="Título" required>
          <textarea class="form-control" name="encabezado" required placeholder="Descripción de la encuesta"></textarea>
          <select name="area" class="form-control" required>
                <option value = "">Selecciona un Área dirigida</option>
                <option value = "1">Direccion de carreras</option>
                <option value = "1">Planeacion</option>
                <option value = "1">Control escolar</option>
              </select>

          <select name="dirigido" class="form-control" required>
                <option value = "">Selecciona  a quien va dirigida</option>
                <option value = "1">Profesores</option>
                <option value = "2">Alumnos</option>
                <option value = "3">Administrativos</option>
                <option value = "4">Profesores y administrativos</option>
                <option value = "5">General</option>
              </select>
        </div>

        <aside>
          <button type="button" class="add btn btn-success" id="add"><span class="glyphicon glyphicon-plus"></span> Nueva pregunta</button>
        </aside>

        <div class="form-group col-md-12" role="listitem">

          <fieldset id="buildyourform">
        </div>
        <input type="submit" name="guardar" class="btn btn-success" value="Guardar">
      </form>
    </div>
  </div>
</body>

</html>

On the save.php sheet I have the following code I can only receive static data and questions, but the options for each question can not be printed.

<?php
require("../conexion.php");

if(isset($_POST['guardar'])){

$titulo = $_POST['titulo'];
$encabezado = $_POST['encabezado'];
$area = $_POST['area'];
$dirige = $_POST['dirigido'].'<br>';

$p = $_POST['numero'];

for ($i=1; $i <=$p; $i++) {

        $pregunta = $_POST["pregunta$i"];

         echo $pregunta.'<br>';



        }
        echo "<br>";    
}
?>

I hope and you can help me :(, Thank you!

link same here is the example

    
asked by Leslie Sharai 25.07.2017 в 20:57
source

1 answer

1

the correct way to receive a dynamic form is by listing Array in php there are different ways to collect an Array in my case I do it in the following way

I sent it through an input with a certain name and the brackets in the following way

<input class="form-control validate[required]" name="nombre[]" />

These brackets indicate that it is an array in case of php does not need to have a number increasing inside the brackets, it is not necessary

already in php you collect it in the following way:

foreach (array_keys($_POST['nombre']) as $key) {
  $nombre = $_POST['nombre'][$key];

  echo "Nombre: $nombre"."<br>";
}

I am a bit bad explaining however I leave you a basic but clear example of what you need.

index.html:

<!DOCTYPE html>
<html lang="es">

<head>
  <title>Dinamicos</title>
  <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
  <link href="http://cdnjs.cloudflare.com/ajax/libs/jQuery-Validation-Engine/2.6.4/validationEngine.jquery.css" rel="stylesheet">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/jQuery-Validation-Engine/2.6.4/jquery.validationEngine.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/jQuery-Validation-Engine/2.6.4/languages/jquery.validationEngine-es.js"></script>
  <style>
    .top-buffer {
      margin-top: 20px;
    }
  </style>
</head>

<body>
  <div id="container ">
    <div class="row-fluid top-buffer">
      <div class="col-lg-6 col-lg-offset-3 text-center">
        <form id="miform" method="post" name="miform" action="guarda.php">
          <table id="tblprod" class="table table-hover table-bordered">
            <thead>
              <tr>
                <th># Registro</th>
                <th>Nombre</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>1</td>
                <td>
                  <div class="form-group col-lg-4">
                    <input class="form-control validate[required]" name="nombre[]" />
                  </div>
                  <div class="form-group col-lg-4">
                    <input class="form-control validate[required]" name="apellido[]" />
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
          <button id="btnadd" class="btn btn-primary">Agregar Nuevo</button>
          <button id="btnsubmit" type="submit" class="btn btn-success">Guardar</button>
        </form>
      </div>
    </div>
  </div>

  <script type="text/javascript">
    $(function() {
      var count = 1;
      jQuery("#miform").validationEngine({
        promptPosition: "centerRight:0,-5"
      });

      $(document).on("click", "#btnadd", function(event) {
        count++;
        $('#tblprod tr:last').after('<tr><td>' + count + '</td><td><div class="form-group col-lg-4"><input class="form-control validate[required]" name=" nombre[]" /></div><div class="form-group col-lg-4"><input class="form-control validate[required]" name="apellido[]" /></div></td></tr>');
        event.preventDefault();

      });

    });
  </script>

</body>

</html>

guarda.php

<?php

foreach (array_keys($_POST['nombre']) as $key) {
  $nombre = $_POST['nombre'][$key];
  $apellido = $_POST['apellido'][$key];

  echo "Nombre: $nombre"."<br>"."Apellido: $apellido"."<br>";
}


?>

With that example you can solve your doubts, I remind you that I only printed the result, but you just do the insert query and it's done.

  

UPDATE

Hello, here I show you how to do the insert according to the example shown above, so you can understand much better, the whole code just did and is fully functional:

guarda.php

<?php
$mysqli = new mysqli("localhost", "root", "", "dbtest");
if ($mysqli->connect_errno) {
    echo "Fallo al conectar a MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";

foreach (array_keys($_POST['nombre']) as $key) {
  $nombre = $_POST['nombre'][$key];
  $apellido = $_POST['apellido'][$key];

  echo "Nombre: $nombre"."<br>"."Apellido: $apellido"."<br>";

  $query = "INSERT INTO usuario VALUES (NULL, '$nombre', '$apellido')";
$mysqli->query($query);
}


?>

I remain attentive

    
answered by 25.07.2017 в 23:53