I am creating a "day" select dropdown. With a selectRange I can do this:
{{ Form::selectRange('day', 1, 31, $day) }}
The problem is, when the form loads, if $day
is not set it selects 1
by default. Is it possible to use selectRange to give them a "Please Choose" option that has a NULL value?
Use Form::select instead.
{{ Form::select('day', array('' => 'Please Choose...') + range(1,31)) }}
Use Form Select with range and array_combine if you want to modify the option value:
{{ Form::select('month', array('all' => 'all') + array_combine(range(1,12),range(1,12)) ) }}
I don't believe there is a way of achieving this with the built in selectRange, however it is possible using form macros. The following macro performs roughly what you're looking for, though may require some cleanup.
Form::macro('selectRangeWithDefault', function($name, $start, $end, $selected = null, $default = null, $attributes = [])
{
if ($default === null) {
return Form::selectRange($name, $start, $end, $selected, $attributes);
}
$items = [];
if (!in_array($default, $items)) {
$items['NULL'] = $default;
}
if($start > $end) {
$interval = -1;
$startValue = $end;
$endValue = $start;
} else {
$interval = 1;
$startValue = $start;
$endValue = $end;
}
for ($i=$startValue; $i<$endValue; $i+=$interval) {
$items[$i . ""] = $i;
}
$items[$endValue] = $endValue;
return Form::select($name, $items, isset($selected) ? $selected : $default, $attributes);
});
Usage is as follows:
{{ Form::selectRangeWithDefault('day', 1, 31, $day, 'Please Choose...') }}
Note that I got the idea and the basis for my code from: https://stackoverflow.com/a/25069699/3492098
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With