Sohaib
Sohaib

Reputation: 1991

drop-down show selected value when editing a row laravel

<div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>From Destination:</strong>
                <select name="from_destination_data" class="form-control">
                    @if ($destinationsData != [])
                        @foreach($destinationsData as $info)
                            <option value="{{$destinationsData[$index]}}">{{$info}}</option>
                        @endforeach
                    @endif
                </select>
            </div>
        </div>

I retrieve the $index of the selected $destinationData and when dd($destinationsData[$index]); I get the result that I need but it doesn't appear when I put it in the value as shown above

Upvotes: 2

Views: 1326

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29278

When constructing your <select> and <options>, you need to set a value for each that can be referenced when editing your record. See the following:

<div class="col-xs-12 col-sm-12 col-md-12">
    <div class="form-group">
        <strong>From Destination:</strong>
        <select name="from_destination_data" class="form-control>
          @foreach($destinationsData as $key => $info)
          <option value="{{ $key }}">{{ $info }}</option>
          @endforeach
        </select>
    </div>
</div>

Setting value="{{ $key }}" will, in this instance, set the value to a 0-based index, which can be referenced when editing:

@foreach($destinationsData as $key => $info)
<option value="{{ $key }}" {{ $record->from_destination_data == $key ? 'selected' : '' }}>{{ $info }}</option>
@endforeach

As long as $record->from_destination_data equals any of the $key iterations, that <option> will have selected="selected", setting it as the default selected option.

Upvotes: 2

Related Questions