Ad

Default Value On Form Select (with Foreach Loop)

So, I want to achieve a <select> like solution where a default value is equal to the value that is currently in the database, so the 'old value'.

1

I have this, where I loop a foreach to fill <option>.:

<select id="size"  name="size" class="form-control">
    @foreach ($sizes as $s)
        <option value="{{ $s->value }}">{{ $s->name }}</option>
    @endforeach
</select>

Now where I want to use this is an edit-form in laravel 5.2 where it fills in this form with the current values from the database for the selected user. My input fields with text fill in correctly but this select doesn't.

2

Working with Laravel forms I know this is possible to set the default value to S. But I don't know how to loop this is foreach...:

{{ Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S') }}

So I need to find a way to set default value with HTML-select tags while in a loop with values from my controller or find a way to loop in Laravel Forms.. Either is good, as long as it works

Ad

Answer

Don't know if this is what You are asking, but if You know current value, You can check it with if statement:

<select id="size"  name="size" class="form-control">
    @foreach ($sizes as $s)
        @if ($s->value == $currentSize)
            <option selected value="{{ $s->value }}">{{ $s->name }}</option>
        @else
            <option value="{{ $s->value }}">{{ $s->name }}</option>
        @endif
    @endforeach
</select>
Ad
source: stackoverflow.com
Ad