如何使用动态输入从动态表单更新数据? 我先尝试从表中删除所有具有id的数据,然后像创建时一样插入数据,但是它始终停留在动态表单的1行上。
赞: 姓名|页面行动 测试1 | 22 |添加更多 Test2 | 24 |去掉 测试3 | 23 |删除
当我保存它时,它只保存带有“ Test1”的行。
更新控制器:
public function update(Request $request, Vote $vote)
{
$request->validate([
'item.*.name' => 'required|string|max:191',
'item.*.page' => 'nullable|string',
]);
if(!$vote->vote_options->isEmpty()) {
VoteOption::where('vote_id', $vote->id)->delete();
//$vote->vote_options()->delete();
}
foreach($request->item as $key => $value) {
$vote->vote_options()->create($value);
return redirect()->route('admin.votes.view');
}
return redirect()->route('admin.votes.options.edit', $vote->id);
}
//编辑
<tbody>
@forelse ($vote_options as $option)
<tr>
<td><input type="text" name="item[{{ $loop->index }}][name]" placeholder="Zde napiš jméno kandidáta" class="form-control form-control-alternative" value="{{ $option->name }}" /></td>
<td><input type="text" name="item[{{ $loop->index }}][page]" placeholder="Zde napiš jméno strany" class="form-control form-control-alternative" value="{{ $option->page }}" /></td>
@if ($loop->first)
<td><button type="button" name="addItem" id="addItem" class="btn btn-success">Přidal další</button></td>
<td style="display: none;" id="voteCount" data-count="{{ $loop->count }}"></td>
@else
<td><button type="button" class="btn btn-danger removeItem">Smazat</button></td>
@endif
</tr>
@empty
<tr>
<td><input type="text" name="item[0][name]" placeholder="Zde napiš jméno kandidáta" class="form-control form-control-alternative" /></td>
<td><input type="text" name="item[0][page]" placeholder="Zde napiš jméno strany" class="form-control form-control-alternative" /></td>
<td><button type="button" name="addItem" id="addItem" class="btn btn-success">Přidal další</button></td>
<td style="display: none;" id="voteCount" data-count="1"></td>
</tr>
@endforelse
</tbody>
JS:
let items = $('#voteCount').data('count') - 1;
$("#addItem").click(function() {
++items;
$("#optionsTable").append('<tr><td><input type="text" name="item[' + items + '][name]" placeholder="Zde napiš jméno kandidáta" class="form-control form-control-alternative" /></td><td><input type="text" name="item[' + items + '][page]" placeholder="Zde napiš jméno strany" class="form-control form-control-alternative" /></td><td><button type="button" class="btn btn-danger removeItem">Smazat</button></td></tr>');
});
$(document).on('click', '.removeItem', function(){
$(this).parents('tr').remove();
});
顺便说一句。没有这行
VoteOption::where('vote_id', $vote->id)->delete();
它运行完美。
感谢任何想法,大概这样我做的不好:/