0

When we create a date field in node form, we can set START and END years to be shown in that date field. If we are creating a date field programatcaly, how do we do that?

I have a date field, my_date, I want to to show only next 5 years from now on. Any help?

$form['my_date'] = array(
  '#type' => 'date',
  '#date_format' => 'd-m-y',
  '#default_value' => format_date($primary_start1, 'custom', $format),
  '#date_type' => DATE_DATETIME,
  '#date_timezone' => date_default_timezone(),
  '#date_format' => 'm/d/Y',
  '#size' => 20,
  '#access' => TRUE,
);

I tried to see structure bu creating a date field and printing the form, but found nothing.

0

We can do it like this...

$form['my_date'] = array(
  '#type' => 'date',
  '#date_format' => 'd-m-y',
  '#default_value' => format_date($primary_start1, 'custom', $format),
  '#date_type' => DATE_DATETIME,
  '#date_timezone' => date_default_timezone(),
  '#date_format' => 'm/d/Y',
  '#size' => 20,
  '#access' => TRUE,
  '#after_build' => array("custom_range_date")
);

using '#after_build' => array("custom_range_date")

function custom_range_date($form_element, &$form_state){
    // We unset the current values
    unset($form_element['year']['#options']);

    // Now we set the range we want
    $max_age = date('Y') - 100; // 100 years ago
    $min_age = date('Y') - 7; // 7 years ago

    // Now we populate the array
    $form_element['year']['#options'] = array();
    foreach (range($max_age, $min_age) as $year){
        $form_element['year']['#options'][$year] = $year;
    }

    // We return our modified element
    return $form_element;
}

SEE: https://www.drupal.org/node/1165138

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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