简体   繁体   中英

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.

While trying auto-select radio buttons based on db values upon Edit , The correct item selects by default, which is the expected result. 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. 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:

{!! 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM