【问题标题】:Laravel add/remove input fields update values problemLaravel 添加/删除输入字段更新值问题
【发布时间】:2020-07-13 15:39:42
【问题描述】:

我在 jquery 中使用添加/删除输入字段,当我想更新值时遇到问题。

在 store() 方法中,foreach 循环获取我添加的所有输入字段,而在 update() 方法中,foreach 循环仅获取第一个输入。

我该如何解决这个问题?

我有两个表“attributes(id,name)”和“attribute_option(id,attribute_id,attribute_value”)。

在edit.balde.php中

<script type="text/javascript">
   $("#add").click(function(){
     addRow();
   }}

   function addRow(){
     $("optionsTable").append('<tr><td><input type="text" name="value[]" class="form-control"</td><td><button type="button" class="remove-tr">Remove</button></td></tr>);
   };

   $(document).on('click','.remove-tr', function(){
     $(this).parents('tr).remove();
   });
</script>

<button type="button" id="add">Add row</button>
@foreach($attribute_options as $key=>$option)
<tr>
   <td>
     <input type="hidden" name="option_id[]" value="{{ $option->id }}">
     <input type="text" name="value[]" value="{{ $option->attribute_value }}"> 
   </td>
   <td>
     <button type="button" class="remove-tr">Remove</button>
   </td>
</tr>
@endforeach

在我的控制器操作中更新()

if($request->has('value)){
  $options = $request->value;
  $option_id = $request->option_id;
  foreach($options as $value){
     AttributeOption::where('id','=',$option_id)->update(array(
      'attribute_value' => $value
     ));
  }
}

【问题讨论】:

  • 在更新()中;输出 dd($request->value) 是什么?
  • value 是数组的类型,所以我认为您应该将选项分配为 $options = $request['value'];

标签: laravel


【解决方案1】:

因为$option_id也是一个数组,因此也必须作为数组读取:

if($request->has('value')){
  $options = $request->value;
  $option_id = $request->option_id;
  foreach($options as $key => $value){
     AttributeOption::where('id','=',$option_id[$key])->update(array(
      'attribute_value' => $value
     ));
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多