[英]Laravel5: Form-model binding - Radio buttons auto select causing problems when creating new record
I'm using Form-Model binding and the same view partial for both creating and editing a user. 我正在使用Form-Model绑定和相同的视图部分来创建和编辑用户。
While trying auto-select radio buttons based on db values upon Edit
, The correct item selects by default, which is the expected result. 尝试在Edit
根据db值自动选择单选按钮时,默认情况下会选择正确的项目,这是预期的结果。 But when I try creating a new user using the same form partial, it gives an error Undefined variable: user
because we didn't pass a $user
variable on the create method, which seems unnecessary. 但是,当我尝试使用相同的partial表单创建新用户时,它会给出错误的Undefined variable: user
因为我们没有在create方法上传递$user
变量,这似乎是不必要的。 How do I fix this? 我该如何解决?
Controller Methods: 控制器方法:
public function create()
{
return view('backend/users/create');
}
public function edit(User $user)
return view('backend/users/edit', compact('user'));
}
Form radio buttons: 表单单选按钮:
{{ Form::radio('level', 1, $user, []) }}
{{ Form::radio('level', 2, $user, []) }}
{{ Form::radio('level', 3, $user, []) }}
It's because you don't have $user
var in create method so try like this: 这是因为在create方法中没有$user
var,所以请尝试如下操作:
{!! Form::radio('level', 1, isset($user) ? $user : null, []) !!}
{!! Form::radio('level', 2, isset($user) ? $user : null, []) !!}
{!! Form::radio('level', 3, isset($user) ? $user : null, []) !!}
I've also put Form::radio
in {!! !!}
我也将Form::radio
放在{!! !!}
{!! !!}
because in L5 {{ }}
will escape all the html tags with htmlentities
. {!! !!}
因为在L5中, {{ }}
将使用htmlentities
转义所有html标签。
But this is still not good way. 但这仍然不是好方法。 If you're passing the model I suppose that you want to bind all form with model's data, so you should bind $user
on the form like this: 如果您要传递模型,我想您想将所有表单与模型的数据绑定,因此应在表单上绑定$user
,如下所示:
@if(isset($user))
{!! Form::model($user, [...]) !!}
@else
{!! Form::open([...]) !!}
@endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.