好的,我有一个带有 selectRange/selectMonth 输入的 laravel 表单,但是我怎样才能让它都长 2 位数字?
因此,对于我的第一个选择范围从 1-31,所有一位数字都类似于:01、02、03、04 等。
我的第一个月是一样的,但有 1-12 个数字。
{{ Form::label('day', 'What''s your date of birth?') }}
{{ Form::selectRange('day', 01, 31, null, array('class' => 'date')) }}
{{ Form::selectMonth('month', null, array('class' => 'month')) }}
{{ Form::selectRange('year', 2014, 1880, null, array('class' => 'year')) }}
在这种情况下,
我建议您使用Form::select
而不是Form::selectRange
。例:
天:
$days = [];
for($i = 1; $i <= 31; $i++){
$val = ($i < 10) ? '0'.$i : $i;
$days[$val] = $val;
}
Form::select('day', $days, '01');
几个月:
$months = [
'01' => 'January',
'02' => 'February',
'03' => 'March',
'04' => 'April',
'05' => 'May',
'06' => 'June',
'07' => 'July',
'08' => 'August',
'09' => 'September',
'10' => 'October',
'11' => 'November',
'12' => 'December'
];
Form::select('month', $months, '01');
Form::selectRange
不支持前导零。因此,您必须自己构建选项并使用正常Form::select
(如void main的答案所述)
最佳做法是编写带有前导零的可重用范围函数。
public function selectRangeLeadingZeros($name, $begin, $end, $selected = null, $options = array()){
$range = array_combine($range = range($begin, $end), $range);
foreach($range as &$value){
$value = str_pad($value, 2, "0", STR_PAD_LEFT);
}
return Form::select($name, $range, $selected, $options);
}
这基本上是 selectRange
方法的内容,并添加了 foreach 循环以将前导零放入其中。
您可以将其放在自定义帮助程序类/文件中或扩展Laravel表单类
你会像现在一样使用它selectRange
Laravel 5 - Laravel Collective HTML
实际上做月份和年份很简单:
{!! Form::selectMonth('month', null, ['class'=>'month']) !!}
{!! Form::selectYear('year', date('Y'), date('Y')-100, null, ['class'=>'year']) !!}
至于Day,我只会做一些类似于@mehedi-pstu-2K9的答案的事情。
您还可以轻松添加格式。对于月份,只需将格式字符串作为第四个参数传递即可。假设您正在获取信用卡信息并希望将其填充为 0:
{!! Form::selectMonth('month', null, ['class'=>'month'], '%m') !!}
至于年份,我们已经传递了一个格式字符串。只需将 date('Y')
的两个实例都更改为 date('y')
(较低的 y),它将是两位数。