Laravel5:表单模型绑定 - 单选按钮自动选择在创建新记录时导致问题

时间:2016-09-01 05:39:55

标签: forms laravel laravel-5

我正在使用表单模型绑定和相同的视图部分来创建和编辑用户。

尝试基于Edit上的db值自动选择单选按钮时, 默认选择正确的项目,这是预期的结果。但是当我尝试使用相同的表单partial创建一个新用户时,它会给出错误Undefined variable: user,因为我们没有在create方法上传递$user变量,这似乎是不必要的。我该如何解决这个问题?

控制器方法:

public function create()
    {
        return view('backend/users/create');
    }
public function edit(User $user)
    return view('backend/users/edit', compact('user'));
}

表单单选按钮:

{{ Form::radio('level', 1, $user, []) }}
{{ Form::radio('level', 2, $user, []) }}
{{ Form::radio('level', 3, $user, []) }}

1 个答案:

答案 0 :(得分:1)

It's because you don't have $user var in create method so try like this:

{!! 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 {!! !!} because in L5 {{ }} will escape all the html tags with htmlentities.

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:

@if(isset($user))
    {!! Form::model($user, [...]) !!}
@else
    {!! Form::open([...]) !!}
@endif