2

I have a date field, birthday, created with the Date module. By default, the selectable years are 1900-2050. This makes no sense for birthdays so I want to change it to only show years from 1900-(current year-18).

How can I do this?

There is a solution for Drupal 7 but that code does not work in Drupal 8 because form_process_date() does not exist in Drupal 8.

This is the full error:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'form_process_date' not found or invalid function name in Drupal\Core\Form\FormBuilder->doBuildForm() (line 993 of core/lib/Drupal/Core/Form/FormBuilder.php).

Here is the code I'm using:

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['birthday']['#process'] = array('form_process_date', 'mymodule_fix_year_range');
3
  • drupal_map_assoc is a really basic function that you could re-make in about a minute, but the link in your question actually contains an example of the replacement method (using the bog standard array_combine()). Is there a reason you can't use that?
    – Clive
    Commented Oct 11, 2017 at 7:46
  • Which widget are you using? Datetime or datelist?
    – mpdonadio
    Commented Oct 11, 2017 at 13:32
  • @mpdonadio Field type: date, Widget: Select list Commented Oct 11, 2017 at 13:34

3 Answers 3

2

Datelist widget accepts relative values using + or -. You can set 1950:-18 as #date_year_range. Which will create options from 1950 to 18 years before the current year.

2
5

@mpdonadio♦'s answer provides the explanation. Here is the actual code I used:

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['field_birthday']['widget'][0]['value']['#date_year_range'] = '1950:2005';
2

You shouldn't need to add a #process to this.

The Select List widget is based around the Datelist element.

Per the docs (and I don't know why the are on that method and not ::getInfo(). You should be able to form alter this, and change the '#date_year_range' key. This is a string value, which defaults to '1900:2050' (min-year:max-year). You would just need to have some logic to build it up in the proper format.

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.