7

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?

3 Answers 3

3

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.

1
  • You may want to expand and write about why you think this would help based on the question.
    – mradcliffe
    Commented Jul 30, 2020 at 15:10
0

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?

0

Add attribute type "month", this will render as

<input type="month">

Of course the modern day Internet Explorer (Safari) doesn't support this. Well it doesn't support date pickers out of the box anyway so... Actually not supported by Firefox either yet :(

  $form['date_to'] = [
    '#title' => 'To',
    '#type' => 'date',
    '#date_date_format' => 'm/Y',
    '#attributes' => ['type'=> 'month']
  ];

Funny how mozilla documentation explains it but doesn't support it its browser: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/month

Your Answer

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

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