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?


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?

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.