Simplify code: Better use of local vars in form alter.

Created on 20 February 2024, 9 months ago

Problem/Motivation

In node_edit_protection_form_alter() we introduce a variable `$class` but then we don't use it.

function node_edit_protection_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {
  $class = $form['#attributes']['class'] ?? NULL;
  if (is_array($class)) {
    if (!empty($form['#attributes']['class']) && array_search('node-form', $form['#attributes']['class'])) {
      $form['#attached']['library'][] = 'node_edit_protection/node_edit_protection';
    }
  }
}

Steps to reproduce

Proposed resolution

function node_edit_protection_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {
  $class = $form['#attributes']['class'] ?? NULL;
  if (is_array($class)) {
    if ($class && array_search('node-form', $class)) {
      $form['#attached']['library'][] = 'node_edit_protection/node_edit_protection';
    }
  }
}

This is only one step in improving this code.
Besides not properly using the local var, there are also more severe problems:

  • array_search() returns 0 if the needle is the first element.
  • Can the class be a string instead of an array? Not sure.
  • Overall the class should not be used as an indicator that this is a node form.
  • We can also wonder if this should be added to other forms.

Remaining tasks

User interface changes

API changes

Data model changes

📌 Task
Status

Active

Version

1.0

Component

Code

Created by

🇩🇪Germany donquixote

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

Comments & Activities

Production build 0.71.5 2024