function Weight::processWeight

Same name in other branches
  1. 9 core/lib/Drupal/Core/Render/Element/Weight.php \Drupal\Core\Render\Element\Weight::processWeight()
  2. 8.9.x core/lib/Drupal/Core/Render/Element/Weight.php \Drupal\Core\Render\Element\Weight::processWeight()
  3. 10 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;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.