0

I have a node type in Drupal 9.4 with lots of fields. The node type has some very simple form alaters to add additional instructions to the node add form. I also add a JavaScript file that shows users how many characters they have used out of a required minimum in the form alter. We use Field Validation to validate the character counts. The form also uses Conditional Fields. None of these modifications directly impact the field I am trying to work with here.

My goal is that when a date is entered into a birthdate field that it will trigger a callback function. The function will trigger Javascript code. At this time however I cannot get the callback to fire.

The fields name is field_birthdate.

  $form['field_birthdate']['widget']['#prefix'] = '<div id="field-birthdate-custom-wrapper">';
  $form['field_birthdate']['widget']['#suffix'] = '</div>';
  $form['field_birthdate']['widget']['#ajax'] = [
          'callback' => '_my_module_custom_age_check_pop_up',
          'disable-refocus' => FALSE,
          'event' => 'change',
          'wrapper' => 'field-birthdate-custom-wrapper',
      ];

The div is getting added to the HTML for the field so I know that the form alter is being called and that some of this code is working correctly. I think I have verified that the callback is not being called by adding Watchdog loggers to the beginning of my the callback.

function _my_module_custom_age_check_pop_up(&$form, FormStateInterface $form_state) {
\Drupal::logger('my_module')->error('Age check pop_up');
$values = $form_state->getValues();
$birthdate = $values['field_birthdate'][0]['value'];
$age  = my_module_custom_age($birthdate, 'Months');
\Drupal::logger('my_module')->error('The age in months is ' . $age_months);
if ($age_months >=  265) {
    \Drupal::logger('my_module')->error('Starting the library');
    $form['#attached']['library'][] = 'my_module/my_module_custom_age_pop_up.js';
}
}

Besides for the logger I implemented in the code I have tried other JS events like onblur and I have verified that there are no errors in the JS console.

I will mention that the field is in two levels of nested field groups. I do not think this is the problem because the div I am adding the field prefix with the same form alter is visible in the HTML.

I would appreciate any help determining why this callback is not firing.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.