I'm trying to create an edit form for my laravel application that shows a list of damage types.
When the form loads, I want to have the value from the database selected (ie $device_destroyed[0]->damage_type)
However if the user submits the form and there are validation errors, I want the old value to be selected instead.
I've tried many different conditions but can't seem to get the logic right. I want to avoid duplicate values being displayed in the select options as well.
Hopefully the below might give an idea of what I'm trying to do:
<select id="damage_type" name="damage_type">
<option value="">Please Select</option>
@for ($i = 0 ; $i < count($damage_types); ++$i)
<option value="{{ $damage_types[$i] }}"
@if(old('damage_type') == $damage_types[$i])
selected
@endif
@if($damage_types[$i] == $device_destroyed[0]->damage_type)
selected
@endif
>{{ $damage_types[$i]}}
</option>
@endfor
</select>
Try this
@if($errors->any() && old('damage_type') == $damage_types[$i])
selected
@elseif($damage_types[$i] == $device_destroyed[0]->damage_type)
selected
@endif
Thanks to @Adrian Edy Pratama for helping arrive at the solution.
Without the extra !($errors->any())
parameter in the elseif condition block, two select options were being selected.
The final solution was:
@if($errors->any() && old('damage_type') == "$damage_types[$i]")
selected
@elseif(!($errors->any()) && ($damage_types[$i] == $device_destroyed[0]->damage_type))
selected
@endif
>{{ $damage_types[$i]}}
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.