Select Range & Month with Default Placeholder

Submitted by soffan - 10 years ago

You can use this when you want to add a placeholder to your Form::selectRange or Form::selectMonth.

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);
});

Form::macro('selectMonthWithDefault', function($name, $selected = null, $default = null, $attributes = [], $format = '%B')
{
    $months = [];

    if ($default !== null) {
        
        $months['NULL'] = $default;

    }

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

    return Form::select($name, $months, isset($selected) ? $selected : $default, $attributes);
});

/* Usage */