TransWikia.com

Creating date field with only month and year

Drupal Answers Asked by Blaine Lang on December 8, 2020

We are using the Form API in a custom module (and not an entity field), how can we easily set the date widget for just year and month data entry?

I’ve tried adding a #date_format attribute but no change:

$form['date_needed'] = array(
  '#type' => 'date',
  '#title' => $this->t('Date Needed'),
  '#date_date_format' => 'Y/m',
);

I have also tried '#date_date_format' => 'd/m/Y' but the date widget still appears asking for YYYY-mm-dd.

Looking at the source code for core/Render/Element/Date.php and stepping though the code, I can see it’s picking up this setting.

The drupal.org doc page has a comment that indicate this should work: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Date.php/class/Date/8.2.x

Any ideas?

2 Answers

We can make this in a hook_form_alter.

$form['DATE_FIELD_MACHINE_NAME']['widget'][0]['value']['#date_date_element'] = 'month';
$form['DATE_FIELD_MACHINE_NAME']['widget'][0]['value']['#date_date_format'] = 'Y-m';

However, there is still a problem of this way: instead of first day of the month, current day will be saved. I cannot figure out how to solve.

Answered by fishfree on December 8, 2020

Your code should work, just tested it in my own form class:

public function buildForm(array $form, FormStateInterface $form_state) {
    return [
      'date_needed' => [
        '#type' => 'date',
        '#title' => $this->t('Date Needed'),
        '#date_date_format' => 'm/Y',
      ],
}

My browser changes the displayed date value as provided in the value of #date_date_format. In the rendered HTML I also see the data-drupal-attribute:

<input data-drupal-selector="edit-date-needed" data-drupal-date-format="m-Y" id="edit-date-needed" name="date_needed" value="" class="form-date hasDatepicker" type="date">

I am testing with Drupal 8.3.4. Perhaps your core version is lower?

Answered by mvdgun on December 8, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP