2

Is there a way to have date/time fields with the date_popup type, but have the time field be something optional for the user to fill in?

I have the UI with both a Date and Time field with the following code:

$form['mygsb_settings']["publish_on_start_date"] = array(
    '#type' => 'date_popup',
    '#title' => "Publish Start Date",
);

But when a user doesn't enter the start time, I get back the following validation error from drupal.

The value input for field Publish Start Date is invalid: The value 2012-03-14 does not match the expected format.

Is there any way to avoid this validation error? Basically, I want to make the time field optional.

Greg

2 Answers 2

1

I needed to allow users to give either a datetime or just a date, so I needed to override the default date_popup behaviour. NOTE: I am not using the date fields provided with the date uri, just the date_popup form element.

You can override the default date_popup validation. The data_popup module applies the validation function during the date_popup_element_process function.

I used a hook_element_info_alter function to append a custom process function AFTER the date_popup_element_process and applied my own validation function. Like so:

function hook_element_info_alter(&$type) {
    $type['date_popup']['#process'][] = 'my_popup_date_process';
}

function my_popup_date_process($element, &$form_state, $form) {
    $element['#element_validate'] = array('my_popup_date_validate');
    return $element;
}

function my_popup_date_validate() {
    if (isset($form_state['values'][$element['#field_name']])) {
        if (trim($form_state['values'][$element['#field_name']][$element['#language']][0]['time']) == '') {
            list($date_format, $time_format) = explode(" ", $element['#date_format']);
            $element['#date_format'] = trim($date_format);
        }
    }
    date_popup_validate($element, $form_state);
}

Removed unneeded code for brevity. Updated validation funciton with an example showing how this could be achieved. This example assumes that there is a space between the data and time formats (ie "d/m/Y H:i:s") and that the date format is first.

0

adding

'#required' => FALSE,

could help .. see forms API

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.