Laravel selectRange blank parameter

I am creating a day drop-down list. With selectRange, I can do this:

{{ Form::selectRange('day', 1, 31, $day) }} 

The problem is that when loading the form, if $day not installed, the default is 1 . Is it possible to use selectRange to provide them with a "Please select" option that is NULL?

+5
source share
6 answers

I do not believe that there is a way to achieve this using the built-in selectRange, however, using macro forms is possible. The following macro does roughly what you are looking for, but may require some cleaning.

 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...') }} 

Please note that I got the idea and foundation for my code: fooobar.com/questions/1200187 / ...

+2
source

Use the :: select form instead.

 {{ Form::select('day', array('' => 'Please Choose...') + range(1,31)) }} 
+5
source

Use the Select form with a range and array_combine if you want to change the parameter value:

 {{ Form::select('month', array('all' => 'all') + array_combine(range(1,12),range(1,12)) ) }} 
+4
source

this one works with a list of backlinks:

 Form::macro('selectRangeWithDefault', function($name, $begin, $end, $selected = null, $default = null, $attributes = []) { if (!is_array($default) || $default === null) { return Form::selectRange($name, $begin, $end, $selected, $attributes); } $range = $default + array_combine($range = range($begin, $end), $range); return Form::select($name, $range, $selected, $attributes); }); 

Example:

 {!! Form::selectRangeWithDefault('year', date('Y'), 1915, $user->getBirthYear(), ['' => 'YYYY']) !!} 

And if you look, how to add a macro: Where to place HTML macros in laravel 5?

0
source

Use form :: select instead of form :: selectRange

Also, in accordance with best practices, you can use the placeholder parameter to create an empty parameter.

 {{ Form::select('day', range(1, 31), null, ['placeholder' => '']) }} 
0
source

use placeholder

  {{ Form::selectRange('day', 1, 31, $day,['class' => 'form-control input-lg','name'=>'day','id'=>'day','placeholder' => 'Please Choose']) }} 
0
source

Source: https://habr.com/ru/post/1200184/


All Articles