将多行从 Laravel 5 中的动态表单保存到数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31629082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save multiple rows to database from dynamic forms in Laravel 5
提问by Hyman Barham
I'm using jQuery to generate two dynamic fields. Each pair of fields is displayed on the page and can have multiple instances. On submit (not ajax), each pair of fields is saved into the their own table row along with Auth::id()
.
我正在使用 jQuery 生成两个动态字段。每对字段都显示在页面上,并且可以有多个实例。在提交(不是 ajax)时,每对字段与Auth::id()
.
There are two forms in the HTML code, both values are entered, user clicks 'Add link' then jQuery creates two hidden fields (these are the ones that get submitted) and data entered appears (appended) visually to #link-list
. The original fields become empty and the process can repeat...
HTML 代码中有两个表单,输入两个值,用户单击“添加链接”,然后 jQuery 创建两个隐藏字段(这些是提交的字段),输入的数据以视觉方式显示(附加)到#link-list
. 原来的字段变空了,这个过程可以重复......
I'm struggling to create an array that is recognised by eloquent to save the data multiple times.
我正在努力创建一个由 eloquent 识别的数组以多次保存数据。
I get the error 'Undefined index: link' or whichever the second input row is in jQuery.
我收到错误“未定义索引:链接”或 jQuery 中的第二个输入行。
Blade/HTML:
刀片/HTML:
{!! Form::open(['route' => ['multiple.store'], 'method' => 'post', 'role'=> 'form', 'class' => 'form']) !!}
<ul id="link-list">
<!-- append new rows -->
</ul>
<div id="newlink" class="form-inline">
<div class="form-group">
{!! Form::text('prestore', null, ['placeholder' => 'Store name', 'class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::text('prelink', null, ['placeholder' => 'Link / URL', 'class' => 'form-control']) !!}
</div>
<div class="form-group">
<button class="btn btn-primary submit new-row" type="button">Add store link</button>
</div>
</div>
<br/><br/>
{!! Form::submit('Submit rows', ['class' => 'btn btn-success submit']) !!}
{!! Form::close() !!}
jQuery/JavaScript
jQuery/JavaScript
$(document).on('click', '.new-row', function() {
var store = $('#newlink input[name=prestore]').val();
var link = $('#newlink input[name=prelink]').val();
console.log(store, link);
$('<li class="not-saved">' +
'<a href="'+link+'">'+store+'</a>' +
'<input type="hidden" name="rows[][link]" value="' + link + '">' +
'<input type="hidden" name="rows[][store]" value="' + store + '">' +
'</li>').appendTo('#link-list').hide().fadeIn(280);
$('input[name=prestore]').val('');
$('input[name=prelink]').val('');
});
Controller:
控制器:
public function store()
{
$input = Input::all();
foreach ($input['rows'] as $row) {
$items = new Multiple([
'user_id' => Auth::id(),
'store' => $row['store'],
'link' => $row['link'],
]);
$items->save();
}
}
回答by Ben Claar
One problem is in your JavaScript element names:
一个问题是你的 JavaScript 元素名称:
<input type="hidden" name="rows[][link]" value="' + link + '">
<input type="hidden" name="rows[][store]" value="' + store + '">
This will generate $rows
like:
这将生成$rows
如下:
[
0 => ["link" => "foo"],
1 => ["store" => "bar"]
]
But your PHP code expects $rows
to be like:
但是你的 PHP 代码$rows
应该是这样的:
[
0 => [
"link" => "foo",
"store" => "bar"
],
1 => [
"link" => "foo",
"store" => "bar"
]
]
One way to generate the expected values is to specify the row keys in your elements:
生成预期值的一种方法是在元素中指定行键:
<input type="hidden" name="rows[0][link]" value="' + link + '">
<input type="hidden" name="rows[0][store]" value="' + store + '">
<input type="hidden" name="rows[1][link]" value="' + link + '">
<input type="hidden" name="rows[1][store]" value="' + store + '">
Obviously this is a bit tricky given the code you've provided, so let me know if you need assistance with that.
显然,鉴于您提供的代码,这有点棘手,所以如果您需要帮助,请告诉我。
回答by Hyman Barham
If this helps anyone else, this is the jQuery required to work with Ben's correct answer:
如果这对其他人有帮助,那么这是使用 Ben 的正确答案所需的 jQuery:
var count = 0;
$(document).on('click', '.new-row', function() {
count++;
var store = $('#newlink input[name=prestore]').val();
var link = $('#newlink input[name=prelink]').val();
if ($('input[name=prestore]').val().length > 2 && $('input[name=prelink]').val().length > 2) {
$('<li class="not-saved">' +
'<a href="' + link + '">' + store + '</a>' +
'<input type="hidden" name="rows[' + count + '][store]" value="' + store + '">' +
'<input type="hidden" name="rows[' + count + '][link]" value="' + link + '">' +
'</li>').appendTo('#link-list').hide().fadeIn(280);
$('input[name=prestore]').val('');
$('input[name=prelink]').val('');
} else {
console.log('At least 3 characters for each field required!');
}
});
I also added a tiny bit of validation so it wont append empty fields
我还添加了一点验证,因此它不会附加空字段
回答by Ben Claar
I agree that this is a problem with your element names, but disagree with Ben's solution. You can keep your JavaScript as-is and handle this in PHP:
我同意这是您的元素名称的问题,但不同意 Ben 的解决方案。你可以保持你的 JavaScript 原样并在 PHP 中处理它:
public function store()
{
$rows = Input::get('rows');
$userId = Auth::id();
for ($i = 0; $i < (count($rows) - 1); $i += 2) {
$item = new Multiple([
'user_id' => $userId,
'link' => $rows[$i]['link'],
'store' => $rows[$i + 1]['store'],
]);
$item->save();
}
}