Laravel 4 Form :: selectMonth前置月份

时间:2014-09-14 18:41:33

标签: php laravel laravel-4

如何将选项添加到laravel

{{ Form::selectMonth('month') }}

结果

<select name="month">
    <option value="1">January</option>
    <option value="2">February</option>
    <option value="3">March</option>
    <option value="4">April</option>
    <option value="5">May</option>
    <option value="6">June</option>
    <option value="7">July</option>
    <option value="8">August</option>
    <option value="9">September</option>
    <option value="10">October</option>
    <option value="11">November</option>
    <option value="12">December</option>
</select>

我想在此前加一个选项值= 0

<select class="form-control" name="month">
    <option value="0">Month</option>
    <option value="1">January</option>
    <option value="2">February</option>
    <option value="3">March</option>
    <option value="4">April</option>
    <option value="5">May</option>
    <option value="6">June</option>
    <option value="7">July</option>
    <option value="8">August</option>
    <option value="9">September</option>
    <option value="10">October</option>
    <option value="11">November</option>
    <option value="12">December</option>
</select>

并设置默认值或选择月份占位符。

2 个答案:

答案 0 :(得分:2)

你不能,所以你必须创建自己的数组:

$months = array(0 => 'Month');

foreach (range(1, 12) as $month)
{
    $months[$month] = strftime($format, mktime(0, 0, 0, $month, 1));
}

将其传递给您的观点:

return View::make('viewname')->with('months', $months);

并使用Form::select()

 {{ Form::select('month', $months) }}

作为表单宏,它可能是:

Form::macro('selectMonthWithDefault', function($name, $options = array(), $format = '%B')
{
    $months = array(0 => 'Month');

    foreach (range(1, 12) as $month)
    {
        $months[$month] = strftime($format, mktime(0, 0, 0, $month, 1));
    }

    return Form::select($name, $months);
});

不要忘记你也可以扩展FormBuilder类并创建一个新的Form::selectMonth()

答案 1 :(得分:1)

在app / macros.php中创建新文件并复制粘贴此行代码

Form::macro('selectMonths', function($name, $options = array(), $format = '%B')
{
    $months = array(0 => 'Month');

    foreach (range(1, 12) as $month)
    {
        $months[$month] = strftime($format, mktime(0, 0, 0, $month, 1));
    }

    return Form::select($name, $months, null, $options);
});

在app / start / global.php中需要macros.php