I have multiple date fields on a node form for which I am using the select widget. The year select list has a range of years that is far too wide for our purposes (1900-present), so we want to limit it. I am able to accomplish this with hook_form_alter, however the fields that are multi-value to not reflect this change when they are loaded with ajax. Here is my current code which gets the first deltas:

public function alterQuarterlyReportForm(&$form, FormState  $form_state, $form_id) {

// form_alter functionality for quarterly reports
if ($form_id == 'node_quarterly_report_form' || $form_id == 'node_quarterly_report_edit_form') {

  // Limiting range of years in date fields on report form
      $form['field_draft_evaluation_date']['widget'][0]['value']['#date_year_range'] = '-3:+3';
      $form['field_draft_protocol_date']['widget'][0]['value']['#date_year_range'] = '-3:+3';
      $form['field_updated_milestone_plandate']['widget'][0]['value']['#date_year_range'] = '-3:+3';
      $form['field_committee_date']['widget'][0]['value']['#date_year_range'] = '-3:+3';
      $form['field_liaison_meeting_dates']['widget'][0]['value']['#date_year_range'] = '-3:+3';
      $form['field_meeting_date']['widget'][0]['value']['#date_year_range'] = '-3:+3'; }}

Obviously these are each set for delta 0, and what I am having trouble figuring out is how to get this working for each additional value that a user wants to enter. I have attempted a few foreach() loops, but I am not getting it right.

1 Answer 1


I think you probably want this:

$fields = [

foreach ($fields as $field) {
  foreach (\Drupal\Core\Render\Element::children($form[$field]) as $index) {
    $form[$field]['widget'][$index]['value']['#date_year_range'] = '-3:+3';

Note that Element::children() returns "The children of an element array are those key/value pairs whose key does not start with a '#'". For the above code, it will return the deltas for multi-value fields.

  • Thank you! This feels very close. It seems that there is another variable where the code affecting the field children should only fire after an ajax call has completed, when the 'Add another item' button has been clicked. As of right now, this does not affect the children, and actually adds an extraneous table row on the form for this field. So I suppose the final step to get this working would be to have some kind of ajax callback?
    – elizoliva
    Commented Jan 18, 2023 at 18:59

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.