Define the selected option with the old input in L

2019-01-17 20:56发布

I have this code:

<select required="required" class="form-control" name="title">
    <option></option>
    @foreach ($titles as $key => $val)
        @if (stristr($key, 'isGroup'))
            <optgroup label="{{ $val }}">
        @else
        <option value="{{ $key }}">{{ $val }}</option>
        @endif
    @endforeach
    </select>

So when the form have errors i use the line Redirect::route('xpto')->withInput()->withErrors($v). But i can't re-populate the select fields. Any way to do this without using JavaScript for example?

11条回答
孤傲高冷的网名
2楼-- · 2019-01-17 21:34
<option value="{{ $key }}" {{ Input::old('title') == $key ? 'selected="selected"' : '' }}>{{ $val }}</option>
查看更多
做自己的国王
3楼-- · 2019-01-17 21:35
<select name="gender" class="form-control" id="gender">
                                <option value="">Select Gender</option>
                                <option value="M" @if (old('gender') == "M") {{ 'selected' }} @endif>Male</option>
                                <option value="F" @if (old('gender') == "F") {{ 'selected' }} @endif>Female</option>
                            </select>
查看更多
Luminary・发光体
4楼-- · 2019-01-17 21:37
      <select class="form-control" name="kategori_id">
        <option value="">-- PILIH --</option>
        @foreach($kategori as $id => $nama)
            @if(old('kategori_id', $produk->kategori_id) == $id )
            <option value="{{ $id }}" selected>{{ $nama }}</option>
            @else
            <option value="{{ $id }}">{{ $nama }}</option>
            @endif
        @endforeach
        </select>
查看更多
霸刀☆藐视天下
5楼-- · 2019-01-17 21:40

Okay, my 2 cents, using the default value of Laravel's old() function.

<select name="type">
    @foreach($options as $key => $text)
        <option @if((int) old('type', $selectedOption) === $key) selected @endif value="{{ $key }}">{{ $text }}</option>
    @endforeach
</select>
查看更多
Evening l夕情丶
6楼-- · 2019-01-17 21:50

Instead of using Input class you can also use old() helper to make this even shorter.

<option {{ old('name') == $key ? "selected" : "" }} value="{{ $value }}">
查看更多
登录 后发表回答