1

I have code that generates a select dropdown with times from 8:00am-6:00pm. Upon selecting an option, and saving the form, the times are saved in the database properly. HOWEVER, I cannot retrieve the times automatically. This is my code so far :

<select value="<?php echo $starttime; ?>" name="data[InvoiceTime][<?php echo $key;?>][starttime]" id="starttime_<?php echo $key+1?>" class="form-control" autocomplete="off">
    <?php
        $time = mktime(0, 0, 0, 1, 1);
        for ($i = 28800; $i < 42600; $i += 900) {  // 1800 = half hour, 86400 = one day
        printf('<option value="%1$sam">%1$sam</option>',
        date('g:i', $time + $i), date('g:i a', $time + $i + 1800));
        }
        for ($i = 43200; $i < 65000; $i += 900) {  // 12pm-6pm
        printf('<option value="%1$spm">%1$spm</option>',
        date('g:i', $time + $i), date('g:i a', $time + $i + 1800));
        }
        ?>
    </select>

Desired output : select "9:00am" and save form 9:00am is saved to db(which happens) reload form  9:00 appears preselected due to data saved in db

Actual output : select "9:00am" and save form 9:00am is saved to db reload form 8:00am appears(default value)

The following code works, but does not generate the option values :

<select value="<?php echo $starttime; ?>" name="data[InvoiceTime][<?php echo $key;?>][starttime]" id="starttime_<?php echo $key+1?>" class="form-control" autocomplete="off">
        <option value="8:00am" <?= ($item['starttime']) == '8:00am' ? 'selected' : '' ?>>8:00am</option>
        <option value="9:00am" <?= ($item['starttime']) == '9:00am' ? 'selected' : '' ?>>9:00am</option>
</select>
Steven
  • 687
  • 1
  • 10
  • 27

1 Answers1

0

You just needed to move your check for the value into the existing code.

However, I have simplified your code quite a bit; I'm not sure what you were trying to accomplish with your printf() statements. gmdate() is happy to work with just seconds (you don't want to use date() as it can deliver unexpected results, based on your current time zone.) If an <option> element doesn't have a value attribute, the contents are used instead, so I've removed it. You should always always separate your PHP from your HTML (ideally more than I've done here, but this is a start.)

And in case you aren't familiar with them, here is some info on the ternary statement and heredoc blocks.

<?php
$start    = 28800;
$stop     = 65000;
$interval = 900;
$options  = "";
for ($seconds = $start; $seconds <= $stop; $seconds += $interval) {
    $time     = gmdate("g:ia", $seconds);
    $selected = ($item["starttime"] === $time) ? " selected" : "";
    $options .= sprintf("<option %s>%s</option>", $selected, $time);
}

echo <<< HTML
<select value="$starttime" name="data[InvoiceTime][$key][starttime]" id="starttime_$key" class="form-control" autocomplete="off">
$options
</select>
HTML;
Community
  • 1
  • 1
miken32
  • 42,008
  • 16
  • 111
  • 154