You are here

protected static function Select2EntityReferenceWidget::prepareFieldValues in Select 2 8

Set's the values to the correct column key.

Parameters

array $values: The input values.

array $element: The render element.

Return value

array Values with the correct keys.

Overrides Select2Widget::prepareFieldValues

File

src/Plugin/Field/FieldWidget/Select2EntityReferenceWidget.php, line 210

Class

Select2EntityReferenceWidget
Plugin implementation of the 'select2' widget.

Namespace

Drupal\select2\Plugin\Field\FieldWidget

Code

protected static function prepareFieldValues(array $values, array $element) {
  if (empty($element['#autocreate'])) {
    return parent::prepareFieldValues($values, $element);
  }
  $handler_settings = $element['#selection_settings'] + [
    'target_type' => $element['#target_type'],
    'handler' => $element['#selection_handler'],
  ];

  /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $handler */
  $handler = \Drupal::service('plugin.manager.entity_reference_selection')
    ->getInstance($handler_settings);
  $options = empty($element['#options']) ? [] : static::getValidReferenceableEntities(array_keys(OptGroup::flattenOptions($element['#options'])), $handler_settings);
  $items = [];
  foreach ($values as $value) {
    if (isset($options[$value])) {
      $items[] = [
        $element['#key_column'] => $value,
      ];
    }
    else {
      if ($handler instanceof SelectionWithAutocreateInterface) {
        $label = substr($value, 4);

        // We are not saving created entities, because that's part of
        // Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::preSave().
        $items[] = [
          'entity' => $handler
            ->createNewEntity($element['#target_type'], $element['#autocreate']['bundle'], $label, $element['#autocreate']['uid']),
        ];
      }
    }
  }
  return $items;
}