You are here

protected function MultiSelect2BoxesAutocompleteWidget::buildInitValues in Select2 Boxes 8

Build initial values.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: Field items object.

Return value

array Initial values array.

Throws

\Drupal\Component\Plugin\Exception\PluginNotFoundException

1 call to MultiSelect2BoxesAutocompleteWidget::buildInitValues()
MultiSelect2BoxesAutocompleteWidget::formElement in src/Plugin/Field/FieldWidget/MultiSelect2BoxesAutocompleteWidget.php
Returns the form for a single field widget.

File

src/Plugin/Field/FieldWidget/MultiSelect2BoxesAutocompleteWidget.php, line 103

Class

MultiSelect2BoxesAutocompleteWidget
Plugin implementation of the 'entity_reference autocomplete-tags' widget.

Namespace

Drupal\select2boxes\Plugin\Field\FieldWidget

Code

protected function buildInitValues(FieldItemListInterface $items) {

  // Prepare required keys, from the entity type definitions.
  $target_type = $this
    ->getFieldSetting('target_type');
  $definition = \Drupal::entityTypeManager()
    ->getDefinition($target_type);
  $id_key = $definition
    ->getKey('id');
  $label_key = $definition
    ->getKey('label');

  // Workaround for User entity type since it doesn't have label entity key.
  if ($target_type == 'user') {
    $label_key = 'name';
  }
  $ids = [];
  $data_table = $definition
    ->getDataTable();

  /** @var \Drupal\Core\Field\EntityReferenceFieldItemList $items */

  /** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $item */
  foreach ($items
    ->getIterator() as $item) {
    $value = $item
      ->getValue();
    if (!empty($value) && isset($value['target_id'])) {
      $ids[] = $item
        ->getValue()['target_id'];
    }
  }
  if (empty($ids)) {
    return [];
  }
  $select = \Drupal::database()
    ->select($data_table, 'init');
  $select
    ->fields('init', [
    $id_key,
    $label_key,
  ]);
  $select
    ->condition($id_key, $ids, 'IN');
  $entities = $select
    ->execute()
    ->fetchAllKeyed();

  // Additional fix for User entity - Anonymous users
  // has no value for "name" column in the database, so we attach it manually.
  if ($target_type == 'user' && !empty($entities) && isset($entities[0])) {
    $entities[0] = $this
      ->t('Anonymous');
  }
  return !empty($entities) ? $entities : [];
}