Archive for the ‘php’ Category

php function to create date and time dropdown / select boxes

Monday, November 17th, 2008


I don’t know about you, but I really do not like building out crazy drop down boxes something about doing a minutes dropdown of 1-60 really annoys me.  It got me to thinking how easy would be to write a simple function to do this thinking for me…  Now I admit the calendar drop down has pretty much rendered this useless, but think about the progressive enhancement, for the love of no javascript’s sake.

I wanted to make something reusable that can be called across a site to build them out and increment dates/time whenever needed.
The function goes as follows:

  1. public function createDateTimeDropDowns ($params=array()) {
  2. $start = isset($params['start']) ? $params['start'] : '00:00:00';
  3. $datetime = new DateTime($start);
  4. $outputHTML = '<option value=""></option>';
  5. for ($i = 0; $i <= $params['limit']; $i ++) {
  6. $selected='';
  7. $value=$datetime->format($params['formatValue']);
  8. if($params['preselected'] == $value){
  9. $selected = 'selected';
  10. }
  11. $outputHTML .= '<option value="'.$value.'" '.$selected.'>'.$datetime->format($params['formatSelect']).'</option>';
  12. $datetime->modify($params['steps']);
  13. }
  14. return $outputHTML;
  15. }

You can call the function to make you pretty dropdowns like this:

  1. $selYear=self::createDateTimeDropDowns(array('start'=>date("Y"),'steps'=>
    '+1 year','limit'=>1,'formatValue'=>'Y','formatSelect'=>'Y','
    preselected'=>$scheduledYear));
  2. $selMonth=self::createDateTimeDropDowns(array('start'=>'January','steps'=>
    '+1 month','limit'=>11,'formatValue'=>'n','formatSelect'=>'M','
    preselected'=>
    $scheduledMonth));
  3. $selDay=self::createDateTimeDropDowns(array('start'=>'March 1','steps'=>
    '+1 day','limit'=>30,'formatValue'=>'j','formatSelect'=>'j','
    preselected'=>$scheduledDay));
  4. $outputHTML = <<< HTML
  5. <div id="scheduler">
  6. <label for="scheduler">Time</label>
  7. <select id="scheduledMonth" name="selMonth">$selMonth</select>
  8. <select name="scheduledDay" id="scheduledDay">$selDay</select>
  9. <select name="scheduledYear" id="selYear">$selYear</select>
  10. </div>
  11. HTML;

You can view this live here.