0

I am creating a custom page with hook_form and using the datatype '#type' => 'date,

I would like to make that field required.

AND, I want it to initially display blank.

Without #default_value specified, the default is today. How do I, in effect, make the default_value NULL?

2 Answers 2

4

You can use a #pre_render function on that field to unset the values and add an empty option on the 3 select boxes.

$form['start_date'] = array(
    '#type' => 'date',
    '#title' => t('Date'),
    '#description' => t('Your field description ...'),
    '#required' => true,
    '#pre_render' => array('_YOUR_MODULE_form_pre_render_date'),
);
function _YOUR_MODULE_form_pre_render_date(&$element)
{
    // Don't put empty values if a date has already been set
    if (date('Ynj') !== implode('', array_values($element['#default_value']))) {
        return $element;
    }

    // Loop through each field, add empty option and unset value
    foreach (array('year', 'month', 'day') as $field) {
        if (!isset($element[$field])) {
            continue;
        }

        unset($element[$field]['#value']);
        $element[$field]['#default_value'] = '0';
        $element[$field]['#options'] = array(
            '0' => '',
        ) + $element[$field]['#options'];
    }

    return $element;
}
2
  • Actually this then presents a problem when validating as I then get the error The specified date is invalid.
    – DanH
    Commented Jan 9, 2014 at 3:37
  • I wonder why you are comparing the default value to today's date as a way to determine if a date has been set. What would set that value?
    – greggles
    Commented Oct 17, 2017 at 23:01
1

As I was having date validation problems using Mike Vranckx answer above, I needed to implement a custom validation method to get around the The specified date is invalid. error.

First add a custom #element_validate function to the form element:

  $form['dob'] = array(
    '#type' => 'date',
    '#title' => t('Date Of Birth'),
    '#weight' => 9,
    '#pre_render' => array(
      '_form_date_empty',
    ),
    '#element_validate' => array('_form_date_empty_validate'),
  );

However it seems that setting this value will prevent the default date_validate() function from running, which still has some value, we just want to make sure it doesn't prevent blank dates:

function _form_date_empty_validate($element, &$form_state, $form) {
  $date = $element['#value'];
  if (($date['year'] || $date['month'] || $date['day'])) {
    date_validate($element, $form_state, $form);
  }
}

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.