我有更新帖子的更新方法和存储帖子的商店方法,更新如下,商店方法类似但存储:
public function update(Request $request, $id){
$post = post::find($request->radiobutton);
$post->title = $request->title;
// ... other columns
$post->save();
Session::flash('success','post edited with success');
return redirect()->back();
}
然后在视图中我在每个单选按钮中显示帖子名称,我还会显示一个单选按钮来创建新帖子:
<form id="editposts" method="post"
action="{{route('posts.update', ['post_id' => $post->id])}}" enctype="multipart/form-data">
{{csrf_field()}}
<div>
@foreach($posts as $post)
<div class="form-check">
<input class="form-check-input radio" type="radio" name="radiobutton" value="{{ $post->id }}" id="{{$post->id}}">
<label class="form-check-label">
{{$post->title}}
</label>
</div>
@endforeach
</div>
<div class="form-check">
<input checked class="form-check-input" type="radio" name="radiobutton" id="create_post"
value="create_post">
<label class="form-check-label">
Create post
</label>
</div>
<!-- form fields, here is the name but are more like description, etc -->
<div class="form-group">
<label>Post title</label>
<input type="text" required class="form-control" value="{{ old('title') }}" name="title" id="tile">
</div>
<input type="submit" id="poststore" value="Create"/>
<input type="submit" id="postupdate" value="Update"/>
</form>
然后用户可以选择单选按钮并编辑现有帖子或者可以选择&#34;创建帖子&#34;单选按钮创建一个新帖子。
如果用户选择单选按钮&#34;创建帖子&#34;并填写一些表单字段,然后单击&#34;创建&#34;如果没有正确填写表单,例如日期格式不正确,则字段不会被清除,因此用户不需要再次引入它们。这很好。
问题:但是当用户选择与现有帖子对应的某个单选按钮时,表单字段将使用JS在数据库中填充帖子存储的信息。如果用户更改表单的某些信息,例如日期,并引入格式不正确的日期,则会显示错误,但字段不清晰,但是&#34;创建帖子&#34;单选按钮变为选中状态,因此用户不会在编辑帖子的上下文中继续更改上下文以创建新帖子。
如果用户点击与现有帖子相对应的单选按钮并输入一些无效信息并点击&#34;更新&#34;您知道吗?保持这个帖子单选按钮选中,而不是&#34;创建帖子&#34;选中单选按钮?
答案 0 :(得分:0)
您可以使用old()
帮助程序来实现此目的:
<input class="form-check-input radio" type="radio" name="radiobutton"
value="{{ $post->id }}" id="{{ $post->id }}"
{{ old('radiobutton') ? 'checked' : ''}}>
如果在旧请求中找到它,则会在输入标记内打印checked
。有关详细信息,请查看有关此主题的Laravel documentation。