How do I bind a radio button value to my model? Laravel 5.3

时间:2016-10-20 19:28:43

标签: laravel-5

I have a form with a couple of radio buttons;

<div class="form-group{{ $errors->has('procurement') ? ' has-error' : '' }} col-md-6">
<label for="procurement" class="col-md-6 control-label">Procurement Type <span class="red">*</span></label><br>

<div class="col-md-12">
    <input id="procurement" type="radio" name="procurement" value="owned"> Owned
    <input id="procurement" type="radio" name="procurement" value="rental"> Rental

    @if ($errors->has('procurement'))
        <span class="help-block">
            <strong>{{ $errors->first('procurement') }}</strong>
        </span>
    @endif
</div>

I am reusing the form for editing purposes so I want to be able to bind the object's value for 'procurement' when I present the form in edit view. I am able to use this bind the values for text inputs;

value="{{ isset($vehicle->model) ? $vehicle->model : old('model') }}"

But this does not work for radios or selects. What should I be doing? I am NOT using the Form facade for this.

Thanks!

1 个答案:

答案 0 :(得分:1)

You can use selected and checked for what you want to do. Just add it to the end of the element, and it will select/check the element.

Something like this for input type radio:

<input id="procurement" type="radio" name="procurement" value="owned" {{ old('model') === "owned" ? 'checked' : (isset($vehicle->model) && $vehicle->model === 'owned' ? 'checked' : '') }}> Owned
<input id="procurement" type="radio" name="procurement" value="rental" {{ old('model') === "owned" ? 'checked' : (isset($vehicle->model) && $vehicle->model === 'rental' ? 'checked' : '') }}> Rental

And this for select options:

<option value="something" {{ old('model') === "something" ? 'selected' : (isset($vehicle->model) && $vehicle->model === 'owned' ? 'selected: '')}}>Something</option>

Side note: I'd recommend making sure that old('something') comes before other possible values when you're filling values in. For instance, you had:

value="{{ isset($vehicle->model) ? $vehicle->model : old('model') }}"

which would override the user's original input with database results (if any, of course) upon a failed submission. So if I was say, updating my name in a text field, and there were errors to the form, it would direct me back to the form and lose my input because the database results are before the old value. Hope that makes sense!