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?

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

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

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.