1

On user registration page, I have added a date field in select list.

In the manage form display tab, I can set the order of the dropdown fields like day/month/year or month/day/year But I am unable to change the format of the date.

Currently in the day dropdown, it is displaying like 1, 2, 3 and I want to change it to 01, 02, 03. Similarly in the month dropdown, it is displaying like, Jan, Feb and I want to display it like January, February.

Is this possible?

3
  • There's no way to do this through configuration, it will require programming. Are you comfortable with PHP? Nov 11, 2019 at 12:01
  • yes. Any hook to alter?
    – Ahmad
    Nov 11, 2019 at 12:22
  • Yes, you can use hook_form_alter(), locate the selector for the date, and amend the labels programmatically. Nov 11, 2019 at 13:42

2 Answers 2

1

If you want to alter the way this component is shown globally, you can implement hook_preprocess_datetime_form(), eg. like this:

function mymodule_preprocess_datetime_form(&$variables) {
  // Ensure there's a month field and it's a select.
  if (isset($variables["content"]["month"]) && $variables["content"]["month"]['#type'] === 'select') {
    foreach ($variables["content"]["month"]['#options'] as $monthNum => $label) {
      if ($monthNum) {
        // Convert month number to unabbreviated name.
        $dateObj = DateTime::createFromFormat('!m', $monthNum);
        $monthName = $dateObj->format('F');
        $variables["content"]["month"]['#options'][$monthNum] = $monthName;
  }
}

}

The code for the day select will be similar.

0

Use hook_form_FORM_ID_alter():

/**
 * Implements hook_form_FORM_ID_alter().
 */
function <your_module>_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // your custom code here
}

You'll need to set the #date_format for your custom date field in the form array.

This entry in the Drupal.org community documentation might help you with that.

The PHP documentation for date formats may also be helpful here.

1
  • The #date_format property is not working in Drupal 8.
    – Ahmad
    Nov 15, 2019 at 8:29

Your Answer

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

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