使用动态输入字段/laravel 和 jQuery 将多行保存到数据库中

Posted

技术标签:

【中文标题】使用动态输入字段/laravel 和 jQuery 将多行保存到数据库中【英文标题】:save multiple rows into database usin dynamic input fields/larave and jQuery 【发布时间】:2021-09-18 20:30:34 【问题描述】:

我想从动态输入字段中插入多行。

所以我使用下面的表格和下面的脚本来动态添加输入字段。

$(document).ready(function() 

  $("body").on("click", ".add_new_frm_field_btn", function() 
    var random = 1 + Math.floor(Math.random() * 1000); //generate random values..
    var index = $(".form_field_outer").find(".form_field_outer_row").length + 1;
    //added data-index and outer..class
    $(".form_field_outer").append(`<div class="col-12 outer" data-index="$index_$random"><div class="card-body form_field_outer_row"> <div class="form-row"><div class="form-group col-md-4"> <label for="inputState">Casting</label><select id="id_casting" class="form-control" name="rows[$index][id_casting]">
    <option selected>Choose...</option><option data-id="$casting->id_casting" value="$casting->id_casting">$casting->nom.' '.$casting->prenom</option> </select></div><div class="form-group col-md-4"><label for="inputState">Type de contrat</label><select id="id_modele_contrat" class="form-control" name="rows[$index][id_modele_contrat]"> <option selected>Choose...</option><option>...</option> </select></div><div class="card-body "><button type="button" class="btn btn-outline-warning mb-1 remove_node_btn_frm_field">Delete</button></div>
    </div></div></div> `);
  );
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<div class="row">
  <div class="col-12">
    <div class="card mb-4">
      <div class="card-body">
        <h5 class="mb-4">Projet</h5>
        <!-- <form id="projetform" method="post" action="ajout_projet" class="myForms"  enctype="multipart/form-data"> -->
        <form method="POST" id="projetform" class="myForms" enctype="multipart/form-data">

           csrf_field() 
          <input type="hidden" id="id_projet" name="id_projet" />
          <div class="form-group">
            <label for="inputAddress">Numéro de projet</label>
            <input type="text" class="form-control" id="numero_projet" name="numero_projet" placeholder="Description">
          </div>
      </div>
    </div>
  </div>
</div>
<div class="row">
  <div class="col-12 col-md-12 col-xl-8 col-left">
    <div class="card mb-4">
      <div class="card-body">
        <button type="button" class="btn btn-outline-primary mb-1 add_new_frm_field_btn">Ajouter un nouveau casting</button>
        </br>
        </br>

        <div class="row">
          <div class="col-12">

            <div class="card mb-4 form_field_outer  ">
              <div class="card-body form_field_outer_row outer" data-index="1">
                <input type="hidden" id="id_projet_casting" name="id_projet_casting" />
                <div class="form-row">
                  <div class="form-group col-md-4">
                    <label for="inputState">Casting</label>
                    <select class="form-control" name="rows[1][id_casting]" id="id_casting">
                      <option selected>Choose...</option>
                      @foreach($castings as $casting)
                      <option data-id="$casting->id_casting" value="$casting->id_casting">$casting->nom.' '.$casting->prenom</option>
                      @endforeach
                    </select>
                  </div>
                  <div class="form-group col-md-4">
                    <label for="inputState">Type de contrat</label>
                    <select id="id_modele_contrat" class="form-control" name="rows[1][id_modele_contrat]">
                      <option selected>Choose...</option>
                      @foreach($models_contrat as $model_contrat)
                      <option data-id="$model_contrat->id_modele_contrat" value="$model_contrat->id_modele_contrat">$model_contrat->modele_contrat</option>
                      @endforeach
                    </select>
                  </div>
                  <div class="card-body ">
                    <button type="button" class="btn btn-outline-warning mb-1 remove_node_btn_frm_field">Delete</button>
                  </div>
                </div>

                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="col-12 col-md-12 col-xl-4 col-right">

  <div class="card mb-4 casting_details ">
    <div class="card-body casting_details2 ">
      <div class="d-flex flex-row mb-3 ">
        <!-- Pictures ot the selected casting will come here-->
      </div>
    </div>
  </div>


</div>
<button type="submit" name="submit" id="submit" class="btn btn-primary mb-1">Add</button>
</div>

Ajax 代码:

 $('#submit').click(function()
          $.ajax(
                url:"route('ajout_projet.store')",
                method:"POST",
                data:$('#projetform').serialize(),
                type:'json',
                success: function(e)
                    console.log(e)
                ,
                error: function(error)
                    console.log(error)
                

           );

      );

我把控制器放进去:

 $data = $request->input('rows');
   dd($data);

当我在前端添加例如 4 个四行的输入字段时,dd($data); 仅显示第一行:

array:1 [
  1 => array:2 [
    "id_casting" => "19"
    "id_modele_contrat" => "1"
  ]
]

虽然它应该显示 4 个额外的输入字段值,例如:

array:4 [
      1 => array:2 [
        "id_casting" => "19"
        "id_modele_contrat" => "1"
      ],
      2 => array:2 [
        "id_casting" => "19"
        "id_modele_contrat" => "1"
      ],
........
    ]

我尝试了许多解决方案,但仍然存在同样的问题 n 它只考虑第一行而不考虑所有额外的输入字段。

我在这一点上卡了一个星期,还不知道该怎么办。

我知道问题出在我的 html 或 jquery 代码中,但我不知道究竟是什么触发了这个问题。

请帮忙

更新

迁移文件:

public function up()
    
        Schema::create('projets', function (Blueprint $table) 
              $table->increments('id_projet');
              $table->string('numero_projet',10);


public function up()
    
        Schema::create('projets_castings', function (Blueprint $table) 
             $table->increments('id_projet_casting');
             $table->integer('id_projet')->nullable()->unsigned();
             $table->integer('id_casting')->nullable()->unsigned();
             $table->integer('id_contrat')->nullable()->unsigned();
             $table->integer('actif')->default('1');
             $table->timestamps();
              $table->foreign('id_projet')->references('id_projet')->on('projets');
               $table->foreign('id_casting')->references('id_casting')->on('castings');
                $table->foreign('id_contrat')->references('id_contrat')->on('contrats');

        );
    

【问题讨论】:

【参考方案1】:

也许可以帮助别人

我通过将 html 更改为

解决了我的问题

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<form method="POST" id="projetform" class="myForms" enctype="multipart/form-data">

   csrf_field() 
  <div class="row">
    <div class="col-12">
      <div class="card mb-4">
        <div class="card-body">
          <h5 class="mb-4">Projet</h5>
          <!-- <form id="projetform" method="post" action="ajout_projet" class="myForms"  enctype="multipart/form-data"> -->

          <input type="hidden" id="id_projet" name="id_projet" />
          <div class="form-group">
            <label for="inputAddress">Numéro de projet</label>
            <input type="text" class="form-control" id="numero_projet" name="numero_projet" placeholder="Description">
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-12 col-md-12 col-xl-8 col-left">
      <div class="card mb-4">
        <div class="card-body">
          <button type="button" class="btn btn-outline-primary mb-1 add_new_frm_field_btn">Ajouter un nouveau casting</button>
          </br>
          </br>

          <div class="row">
            <div class="col-12">

              <div class="card mb-4 form_field_outer  ">
                <div class="card-body form_field_outer_row outer" data-index="1">
                  <input type="hidden" id="id_projet_casting" name="id_projet_casting" />
                  <div class="form-row">
                    <div class="form-group col-md-4">
                      <label for="inputState">Casting</label>
                      <select class="form-control" name="rows[1][id_casting]" id="id_casting">
                        <option selected>Choose...</option>
                        @foreach($castings as $casting)
                        <option data-id="$casting->id_casting" value="$casting->id_casting">$casting->nom.' '.$casting->prenom</option>
                        @endforeach
                      </select>
                    </div>
                    <div class="form-group col-md-4">
                      <label for="inputState">Type de contrat</label>
                      <select id="id_modele_contrat" class="form-control" name="rows[1][id_modele_contrat]">
                        <option selected>Choose...</option>
                        @foreach($models_contrat as $model_contrat)
                        <option data-id="$model_contrat->id_modele_contrat" value="$model_contrat->id_modele_contrat">$model_contrat->modele_contrat</option>
                        @endforeach
                      </select>
                    </div>
                    <div class="card-body ">
                      <button type="button" class="btn btn-outline-warning mb-1 remove_node_btn_frm_field">Delete</button>
                    </div>
                  </div>


                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</form>


</div>
<button type="submit" name="submit" id="submit" class="btn btn-primary mb-1">Add</button>
</div>

【讨论】:

以上是关于使用动态输入字段/laravel 和 jQuery 将多行保存到数据库中的主要内容,如果未能解决你的问题,请参考以下文章

laravel 中动态输入字段的验证

在 Laravel 5 中将多行从动态表单保存到数据库

如何使laravel中的动态表单字段可填写

在动态创建的输入上使用laravels {{old}}

在 Laravel 5 中验证动态添加的输入字段

使用 jquery 验证动态输入字段