Optimize hook_field_widget_single_element_form_alter

Created on 3 February 2025, about 2 months ago

Problem/Motivation

hook_field_widget_single_element_form_alter performs unnecessary logic if there is no alt text field or the user does not have permission

    // Attach JS.
    $element['#attached']['library'][] = 'ai_image_alt_text/alt_text';
    // Get the entities language or the sites default language.
    $form_object = $form_state->getFormObject();
    $config = \Drupal::config('ai_image_alt_text.settings');
    $lang = method_exists($form_object, 'getEntity') ? $form_object->getEntity()->language()->getId() : \Drupal::languageManager()->getDefaultLanguage()->getId();
    $element['#attached']['drupalSettings']['ai_image_alt_text']['lang'] = $lang;
    $element['#attached']['drupalSettings']['ai_image_alt_text']['autogenerate'] = $config->get('autogenerate');
    $element['#attached']['drupalSettings']['ai_image_alt_text']['hide_button'] = $config->get('hide_button');

    // Only run if alt text field is enabled.
    if (empty($element['#alt_field'])) {
      return;
    }

    // Only show if the user has permission to generate alt text.
    if (!\Drupal::currentUser()->hasPermission('generate ai alt tags')) {
      return;
    }

Proposed resolution

Move this code to _after_ return checks

    // Attach JS.
    $element['#attached']['library'][] = 'ai_image_alt_text/alt_text';
    // Get the entities language or the sites default language.
    $form_object = $form_state->getFormObject();
    $config = \Drupal::config('ai_image_alt_text.settings');
    $lang = method_exists($form_object, 'getEntity') ? $form_object->getEntity()->language()->getId() : \Drupal::languageManager()->getDefaultLanguage()->getId();
    $element['#attached']['drupalSettings']['ai_image_alt_text']['lang'] = $lang;
    $element['#attached']['drupalSettings']['ai_image_alt_text']['autogenerate'] = $config->get('autogenerate');
    $element['#attached']['drupalSettings']['ai_image_alt_text']['hide_button'] = $config->get('hide_button');

Remaining tasks

User interface changes

API changes

Data model changes

πŸ“Œ Task
Status

Active

Version

1.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States mglaman WI, USA

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024