diff --git a/ill_corporate_forms.module b/ill_corporate_forms.module index 2161ab5..8df2986 100644 --- a/ill_corporate_forms.module +++ b/ill_corporate_forms.module @@ -12,6 +12,7 @@ use Drupal\Core\Form\FormStateInterface; */ function ill_corporate_forms_form_node_ill_institution_request_form_alter(array &$form, FormStateInterface $form_state, string $form_id): void { _ill_corporate_forms_add_item_type_states($form); + $form['#validate'][] = '_ill_corporate_forms_validate_partner_email'; } /** @@ -19,6 +20,7 @@ function ill_corporate_forms_form_node_ill_institution_request_form_alter(array */ function ill_corporate_forms_form_node_ill_institution_request_edit_form_alter(array &$form, FormStateInterface $form_state, string $form_id): void { _ill_corporate_forms_add_item_type_states($form); + $form['#validate'][] = '_ill_corporate_forms_validate_partner_email'; } /** @@ -88,3 +90,44 @@ function _ill_corporate_forms_add_item_type_states(array &$form): void { } } +/** + * Validates that the submitted email matches the partner organization's ILL email. + */ +function _ill_corporate_forms_validate_partner_email(array &$form, FormStateInterface $form_state): void { + $partner_value = $form_state->getValue('field_ill_partner_organization'); + $email_value = $form_state->getValue('field_ill_req_email'); + + // Extract the partner node ID. + $partner_nid = NULL; + if (is_array($partner_value) && isset($partner_value[0]['target_id'])) { + $partner_nid = $partner_value[0]['target_id']; + } + + // Extract the submitted email. + $submitted_email = ''; + if (is_array($email_value) && isset($email_value[0]['value'])) { + $submitted_email = $email_value[0]['value']; + } + elseif (is_string($email_value)) { + $submitted_email = $email_value; + } + + if (empty($partner_nid) || empty($submitted_email)) { + $form_state->setErrorByName('field_ill_partner_organization', + t('There is an error with the selected Partner Org, It may not be configured correctly.')); + return; + } + + // Load the partner institution and compare emails. + $partner_node = \Drupal::entityTypeManager()->getStorage('node')->load($partner_nid); + if (!$partner_node || $partner_node->bundle() !== 'ill_institution') { + return; + } + + $partner_email = $partner_node->get('field_ill_email')->value; + if (!empty($partner_email) && mb_strtolower($submitted_email) !== mb_strtolower($partner_email)) { + $form_state->setErrorByName('field_ill_req_email', + t('The email address entered does not match the ILL email on file for the selected partner organization.')); + } +} +