BigJobbies
BigJobbies

Reputation: 4055

Laravel 4 - Input::old for standard select HTML

I was wondering if someone could help me out.

Im trying to list all years from 1970 until the current year without having to come into the code each year and update it.

I am using the following code to achieve this, but i am unsure of how to use the Input::old('year') with it.

$currentYear = date("Y");
$years = range( $currentYear, 1970 );

echo '<label for="year">Year</label>';
echo '<select name="year" id="year">';
echo '  <option value="">Please Select</option>';
foreach( $years as $year ) {
    echo '<option value="' . $year . '">' . $year . '</option>';
}
echo '</select>';

Any help would be greatly appreciated.

Upvotes: 0

Views: 2845

Answers (1)

Altrim
Altrim

Reputation: 6756

If you are trying to re-populate a form after checking it for validation errors (in this case the select input) what you can do is first create a method in a Model (or somewhere else where it suits you) that generates the year range like this

 public static function getRange()
 {
   return array_combine(range(date("Y"), 1970), range(date("Y"), 1970));
 }

The code above will produce an array like this one (from current year to 1970)

Array ( 
[2013] => 2013 
[2012] => 2012 
[2011] => 2011 
[2010] => 2010 
[2009] => 2009 
[2008] => 2008 
...
[1970] => 1970)

Then in your view you can create the select input using the Form class

<?php echo Form::select('year', Model::getRange());?>

The first parameter is the name and the second one accepts an array that will populate the select input, in this case we populate it from our "Model" by calling the getRange() method that returns the above array.

And then in your controller where you check the validation if an error happens

return Redirect::to('form')->withInput();

Here the withInput() method takes care of the old input and your form will have the correct selected option.

Hope this helps.

Upvotes: 3

Related Questions