Reputation: 1057
I have this code in Laravel-5.8
Controller:
public $leave_applicable_genders = [
"1" => "Both",
"2" => "Male",
"3" => "Female",
];
public function create()
{
$leavetype = new HrLeaveType();
return view('leave.leave_types.create')
->with('leavetype', $leavetype)
->with('leave_applicable_genders', $this->leave_applicable_genders);
}
view:
<td width="15%">
<select class="form-control select2bs4" data-placeholder="Select Applicable Gender" tabindex="1" name="leave_applicable_gender[]">
@foreach($leave_applicable_genders as $k => $leave_applicable_gender)
<option value="{{$k}}" @if(old("leave_applicable_gender") == "$k") selected @endif>{{$leave_applicable_gender}}</option>
@endforeach
</select>
</td>
How do I set the default value of the select dropdown option to 1 (Both)?
The old() helper is not working. How do I rectify this?
Thanks
Upvotes: 0
Views: 1447
Reputation: 2545
For number 1 - by default it will be selected as it's the first element in leave_applicable_gender
array.
For number 2 - you can try this
@foreach($leave_applicable_genders as $k => $leave_applicable_gender)
<option value="{{ $k }}" {{ in_array($k, old("leave_applicable_gender") ?? []) ? 'selected' : '' }}>{{ $leave_applicable_gender }}</option>
@endforeach
Edited Answer
Why you need to make this select input as multiple select. User only need to select on option so my suggestion would be
<select class="form-control select2bs4" data-placeholder="Select Applicable Gender" tabindex="1" name="leave_applicable_gender">
@foreach($leave_applicable_genders as $k => $leave_applicable_gender)
<option value="{{$k}}" {{ old("leave_applicable_gender") == $k ? 'selected' : '' }}>{{$leave_applicable_gender}}</option>
@endforeach
</select>
Also, first selected option will be both
.
Upvotes: 0
Reputation: 4992
If you pass second argument to old()
function it will be returned by default. So you can do following:
<td width="15%">
<select class="form-control select2bs4" data-placeholder="Select Applicable Gender" tabindex="1" name="leave_applicable_gender[]">
@php($val = old('leave_applicable_gender', [1])) {{-- 1 for 'Both' --}}
@foreach($leave_applicable_genders as $k => $leave_applicable_gender)
<option value="{{$k}}" @if(in_array($k,$val)) selected="" @endif>{{$leave_applicable_gender}}</option>
@endforeach
</select>
</td>
By setting value
old()
function doesn't run on everyforeach
iteration
Upvotes: 0