function OptionsWidgetBase::massageFormValues

Same name and namespace in other branches
  1. 11.x core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/OptionsWidgetBase.php \Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase::massageFormValues()

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/OptionsWidgetBase.php, line 125

Class

OptionsWidgetBase
Base class for the 'options_*' widgets.

Namespace

Drupal\Core\Field\Plugin\Field\FieldWidget

Code

public function massageFormValues(array $values, array $form, FormStateInterface $form_state) : array {
  // Check if values are already in delta => [column => value] format.
  $first_value = reset($values);
  if (is_array($first_value) && array_key_exists($this->column, $first_value)) {
    return array_values(array_filter($values, fn($item) => $item[$this->column] !== '_none'));
  }
  // Filter out unchecked checkbox values (integer 0) and the '_none' option,
  // then normalize to a sequential array. Use strict comparison because
  // 0 == 'any string'.
  $values = array_values(array_filter($values, fn($item) => $item !== 0 && $item !== '_none'));
  // Drupal\Core\Field\WidgetBase::submit() expects values as an array of
  // values keyed by delta first, then by column, while widgets return the
  // opposite. Transpose selections from field => delta to delta => field.
  $items = [];
  foreach ($values as $value) {
    $items[] = [
      $this->column => $value,
    ];
  }
  return $items;
}

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