Score:-1

Formatting date field with the Form API

il flag

Hi there I'm using drupal 9.x and the forms api to generate a dynamic form. Altough I'm living in the Netherlands where the date format standard is 'dd/mm/yyyy'. I've looked around on the internet for recent ways to modify that format in the html input. But all ways seems to be deprecated cause they don't seem to work for me. I've tried stuff like:

$form['birthdate'] = [
  '#type' => 'date',
  '#title' => $this->t('Your date of birth'),
  '#date_date_format' => 'd-m-Y',
  // and
  '#dateformat' => 'd-m-Y',
];

But none of those seems to work. All other ways that I've found are from 2017 and below. Which seems to deprecated for me.

Score:0
cn flag

I think you can say it is deprecated. Since Datetime is a core module you can use its form element datetime:

$form = [
  '#type' => 'datetime',
  '#default_value' => new DrupalDateTime('2000-01-01 00:00:00'),
  '#date_date_element' => 'date',
  '#date_time_element' => 'none',
  '#date_year_range' => '2010:+3',
  '#date_timezone' => 'Asia/Kolkata',
];

Drupal is using HTML5 forms and the localization is mostly client-side.

The datetime form element is very well documented. I took the example from this API page, which by the way is exactly your use case of a date only field.

Jorn Reed avatar
il flag
So what you basically do there, is before you define the $form fields, you overwrite the html5 client side datetime stuff, and overwrite it with whatever timezone/format you want?
4uk4 avatar
cn flag
This is an example from the API page. You don't need to add the time zone to the form element if you want to use the local timezone of the PHP settings.
Jorn Reed avatar
il flag
I'm trying to use it now, but I can't get it to work because it can't find it by the right namespace when using DrupalDateTime()
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.