0

I'm using the Form API to create a Date of Birth field with lists for month, day and year.

$form['dob'] = array(
    '#type' => 'date_select',
    '#title' => t('Date of birth'),
    '#default_value' => '',
    '#date_format' => 'm-d-Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '-100:+0',
    '#required' => TRUE,
);

Sine the default value is blank this outputs the following:

enter image description here

How can I alter the labels? Specifically I want to get rid of the '-' characters so it looks more like this

enter image description here

1 Answer 1

2

There might be better way to do this, but one method would be to run an #after_build function that will alter the first '' placeholder date label option to your liking. For example:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {     
  $form['dob'] = array(
    '#type' => 'date_select',
    '#title' => t('Date of birth'),
    '#default_value' => '',
    '#date_format' => 'm-d-Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '-100:+0',
    '#required' => TRUE,
  );
  $form['dob']['#after_build'][] = 'MYMODULE_myform_dob_after_build';
}

// Alter the date component option so the first placeholder element has the new label.
function MYMODULE_myform_dob_after_build(&$form, &$form_state) {
  $form['day']['#options'][''] = t('Day');
  $form['month']['#options'][''] = t('Month');
  $form['year']['#options'][''] = t('Year');
  return $form;
}

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.