user1935348
user1935348

Reputation: 11

Timepicker that removes times as they're selected (ajax)

I'm building a booking form for a moving business that uses a calendar combined with a start and end time. I built the timepicker with Formidable Pro, and it allows me to check "unique" on time fields which automatically removes them on the selected date. However it doesn't automatically remove the times from within the range between start and end times (ie: if someone chooses to rent a truck from 1am-3am I need 1am,2am,and 3am to be removed from future options but right now it only removes 1am and 3am) . I need to write ajax to remove the in-between times from the options. I'm not sure where to begin. This is the current ajax_time_ options function. Any push in the right direction would be appreciated.

function ajax_time_options(){
    global $frmpro_settings, $frmdb, $wpdb;

    //posted vars = $time_field, $date_field, $step, $start, $end, $date, $clock
    extract($_POST);

    $time_key = str_replace('field_', '', $time_field);
    $date_key = str_replace('field_', '', $date_field);
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', trim($date)))
        $date = FrmProAppHelper::convert_date($date, $frmpro_settings->date_format, 'Y-m-d');
    $date_entries = FrmEntryMeta::getEntryIds("fi.field_key='$date_key' and meta_value='$date'");

    $opts = array('' => '');
    $time = strtotime($start);
    $end = strtotime($end);
    $step = explode(':', $step);
    $step = (isset($step[1])) ? ($step[0] * 3600 + $step[1] * 60) : ($step[0] * 60);
    $format = ($clock) ? 'H:i' : 'h:i A';

    while($time <= $end){
        $opts[date($format, $time)] = date($format, $time);
        $time += $step;
    }

    if($date_entries and !empty($date_entries)){
        $used_times = $wpdb->get_col("SELECT meta_value FROM $frmdb->entry_metas it LEFT JOIN $frmdb->fields fi ON (it.field_id = fi.id) WHERE fi.field_key='$time_key' and it.item_id in (". implode(',', $date_entries).")");

        if($used_times and !empty($used_times)){
            $number_allowed = apply_filters('frm_allowed_time_count', 1, $time_key, $date_key);
            $count = array();
            foreach($used_times as $used){
                if(!isset($opts[$used]))
                    continue;

                if(!isset($count[$used]))
                    $count[$used] = 0;
                $count[$used]++;

                if((int)$count[$used] >= $number_allowed)
                    unset($opts[$used]);
            }
            unset($count);
        }
    }

    echo json_encode($opts);
    die();
}    

Upvotes: 1

Views: 127

Answers (0)

Related Questions