Reputation: 746
I have a drop down select input on a form. I am repopulating the form with the previous values from the database.
Currently the drop downs are as follows $selectedStart/$selectedEnd are the values being returned from the database. The value returns as 7:00:00 for 7:00am
html/php
<option value="7:00:00"<?php if ($selectedStart == '7:00:00') echo ' selected="selected"'; ?>>7:00am</option>
<option value="7:15:00"<?php if ($selectedStart == '7:15:00') echo ' selected="selected"'; ?>>7:15am</option>
<option value="7:30:00"<?php if ($selectedStart == '7:30:00') echo ' selected="selected"'; ?>>7:30am</option>
<option value="7:45:00"<?php if ($selectedStart == '7:45:00') echo ' selected="selected"'; ?>>7:45am</option>
<option value="8:00:00"<?php if ($selectedStart == '8:00:00') echo ' selected="selected"'; ?>>8:00am</option>
etc…
I need this to happen for the hours from 7am to 10pm. So when this form loads it builds the two drop downs with all the available times but with the returned value from the database. I was manually typing in these values but figured the if statement didn't need to run 100 times for these two drop downs , and then tried a for loop but ran into a problem of adding increments of 15, 3 times and then adding 1 to the first number etc. I have done this with jquery in the past, however this needs to be a php solution.
Upvotes: 0
Views: 97
Reputation: 4124
I would do it like this..
<select name="selection"><?php
$menu = array("-Enter T-Shirt Size-", "Small", "Medium", "Large", "X-Large", "Do not want a t-shirt");
$count = count($menu);
for($i = 0; $i < $count; $i++)
{
?><option><?php if (isset($menu[$i])){ echo $menu[$i]; }?></option><?php
}
?>
<option><?php if (isset($_POST['selection'])){ echo $menu[1]=($_POST['selection']); }?></option>
</select>
Just an example, you will have to changed it to whatever info you want..
Upvotes: 1
Reputation: 219804
$selectedStart = '07:00:00';
$start = new DateTime('7am');
$end = new DateTime('10:15pm');
$interval = new DateInterval('PT15M');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
?>
<option value="<?php echo $dt->format("H:i:s"); ?>"<?php if ($selectedStart == $dt->format("h:i:s")) echo ' selected="selected"'; ?>><?php echo $dt->format("g:ia"); ?></option>
<?php
}
What this does is create a start time and end time as DateTime objects. The end time needs to be one period interval (i.e. 15 minutes) longer because PHP stops on the last interval and does not consider it part of the loop. It then creates an interval of 15 minutes and uses all of it to create a DatePeriod object. It then loops through each date period and echo's it out in an <option>
.
Upvotes: 2