Widget loads references that it never uses, causing increased memory usage

Created on 4 April 2025, 3 days ago

Problem/Motivation

The OptionsShsWidget loads references that it never uses. In OptionsShsWidget we have the following code:

    $element = parent::formElement($items, $delta, $element, $form, $form_state);
    if (isset($form_state->getBuildInfo()['base_form_id']) && ('field_config_form' === $form_state->getBuildInfo()['base_form_id'])) {
      // Do not display the shs widget in the field config.
      return $element;
    }

    // Rewrite element to use a simple textfield.
    $element['#type'] = 'textfield';
    unset($element['#options']);

Note that the element type is set to textfield and the #options are unset. The parent OptionsSelectWidget::formElement() sets the '#options' via OptionsWigetBase::getOptions which fetches all possible references for the field. These references are never used and discarded as shown above since they are fetched on widget load via JS.

This adds up if one has several shs widgets on one page, causing needlessly high memory usage on the initial form load.

Steps to reproduce

N/A

Proposed resolution

Since the references from getOptions() are never used, one can override that method from OptionsWidgetBase to just return an empty array, this can be done in OptionsShsWidget::getOptions():

/**
   * {@inheritDoc}
   */
  protected function getOptions(FieldableEntityInterface $entity): array {
    // We request data when the widget loads in the frontend, the
    // OptionsSelectWidget::formElement() calls this method which fetches the options
    // that are never used on the first load, thus we can return an empty array
    // here.
    return $this->options = [];
  }

Remaining tasks

User interface changes

N/A

API changes

N/A

Data model changes

N/A

🐛 Bug report
Status

Active

Version

2.0

Component

Code

Created by

🇸🇮Slovenia miha.wagner

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