You are here

public static function Weight::processWeight in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Render/Element/Weight.php \Drupal\Core\Render\Element\Weight::processWeight()

Expands a weight element into a select/number element.

1 call to Weight::processWeight()
WeightTest::testProcessWeight in core/tests/Drupal/KernelTests/Core/Render/Element/WeightTest.php
Tests existing #default_value value in #options list.

File

core/lib/Drupal/Core/Render/Element/Weight.php, line 50

Class

Weight
Provides a form element for input of a weight.

Namespace

Drupal\Core\Render\Element

Code

public static function processWeight(&$element, FormStateInterface $form_state, &$complete_form) {

  // If the number of options is small enough, use a select field. Otherwise,
  // use a number field.
  $type = $element['#delta'] <= \Drupal::config('system.site')
    ->get('weight_select_max') ? 'select' : 'number';
  $element = array_merge($element, \Drupal::service('element_info')
    ->getInfo($type));
  $element['#is_weight'] = TRUE;
  if ($type === 'select') {
    $weights = [];
    for ($n = -1 * $element['#delta']; $n <= $element['#delta']; $n++) {
      $weights[$n] = $n;
    }
    $default_value = (int) $element['#default_value'];
    if (!isset($weights[$default_value])) {
      $weights[$default_value] = $default_value;
      ksort($weights);
    }
    $element['#options'] = $weights;
  }
  else {

    // Use a field big enough to fit most weights.
    $element['#size'] = 10;
  }
  return $element;
}