Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel selectRange blank option

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?

like image 900
andrewtweber Avatar asked Aug 13 '14 05:08

andrewtweber


3 Answers

Use Form::select instead.

{{ Form::select('day', array('' => 'Please Choose...') + range(1,31)) }}
like image 166
PunNeng Avatar answered Sep 28 '22 16:09

PunNeng


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)) ) }}
like image 21
Nguyen Hiep Avatar answered Sep 28 '22 18:09

Nguyen Hiep


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

like image 33
akrist Avatar answered Sep 28 '22 18:09

akrist