我尝试了一些方法来显示错误消息。这个想法是用户可以为他的产品添加标签。我的主视图上有一张列出所有产品的表格。表格的每一行都有一个复选框,用户可以选择他想要的任何产品,并在下一页上为这些产品添加一些标签。
我的问题是,我想显示一条提示消息,告诉用户,他还没有选中任何复选框。仅此而已。目前,他被引导至下一页,但未选择任何产品。
<小时/>我的尝试
这就是 Controller 功能,如果用户提交表单,就会被定向到该功能。
公共(public)函数edit() {
// some non important controller code
if(count(Input::get('id')) == 0)
{
Session::flash('danger', 'Sie haben kein Produkt gewählt!');
return redirect()->back();
}
else
{
return view('layout.edit.productedit', [
'ids' => $data, // non important variables
'products' => $product_name
]);
}
}
在我看来:
@if (Session::has('danger'))
<div class="alert alert-danger">{{ Session::get('danger') }}</div>
@endif
效果不太好。用户会收到显示的错误消息,但如果他做的一切正确,下一页也会收到此错误消息,并且标记请求不再起作用。
所以我需要另一种方法来检查用户是否选择了任何复选框并告诉他,他需要至少选择一个复选框才能继续添加标签。
也许使用 Javascript/Jquery 解决方案或 Laravel 中的其他方式。
感谢您抽出宝贵的时间,我很抱歉我的英语不好。
最佳答案
我不会像这样手动验证输入,而是使用 validate()
方法,
public function edit(Request $request, $id)
{
$this->validate($request, [
'title' => 'required|string'
'mycheckbox' => 'accepted'
]);
// if user passes the validation above, the code here will be executed
// Otherwise user will be redirected back to previous view with old input and validation errors.
return view('my-view');
}
在您看来,您可能会收到如下错误:
@if (session()->has('title'))
<div class="alert alert-danger">{{ session()->first('mycheckbox') }} </div>
@endif
@if (session()->has('mycheckbox'))
<div class="alert alert-danger">{{ session()->first('mycheckbox') }} </div>
@endif
阅读official documentation和 myanswer查看其他示例。
关于javascript - 如果没有选中任何复选框,则显示错误消息 - Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37544700/