简体   繁体   中英

Laravel Custom Form Select Macro

Please help me with this custom select macro that I've got from this website . This code is working fine when you add the start value less that the end value.

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[''] = $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);
});

When adding greater than value from start value and less in the end value it breaks. Please help me fix this code guys

If your startvalue is bigger than your endvalue, you set 'start=end', and 'end=start'. If you want (need) to loop from the start to the endvalue, you need to increase every time with '1'. However, if you set the interval to '-1', and you begin from your startvalue (which is now smaller than the endvalue), your loop will never stop.

change

if($start > $end) {  
$interval = -1;
$startValue = $end; 
$endValue = $start;

into

if($start > $end) {
$interval = 1;
$startValue = $end;
$endValue = $start;

to make it work.

edit: explanation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM