You are here

public static function SynonymsEntitySelect::elementSynonymsEntitySelect in Synonyms 8

Form element process callback for 'synonyms_entity_select' type.

File

src/Element/SynonymsEntitySelect.php, line 69

Class

SynonymsEntitySelect
Form element for synonyms-friendly entity select.

Namespace

Drupal\synonyms\Element

Code

public static function elementSynonymsEntitySelect(array &$element, FormStateInterface $form_state, array &$complete_form) {
  $options = [];
  $selection = \Drupal::service('plugin.manager.entity_reference_selection')
    ->getInstance([
    'target_type' => $element['#target_type'],
    'target_bundles' => $element['#target_bundles'],
    'entity' => NULL,
  ]);
  $bundle_info = \Drupal::getContainer()
    ->get('entity_type.bundle.info')
    ->getBundleInfo($element['#target_type']);
  $referenceable_entities = $selection
    ->getReferenceableEntities();
  $entities = [];
  foreach ($referenceable_entities as $bundle_entity_ids) {
    $entities = array_merge($entities, array_keys($bundle_entity_ids));
  }
  if (!empty($entities)) {
    $entities = \Drupal::entityTypeManager()
      ->getStorage($element['#target_type'])
      ->loadMultiple($entities);
  }
  foreach ($referenceable_entities as $bundle => $entity_ids) {
    $synonyms = \Drupal::getContainer()
      ->get('synonyms.behavior.select')
      ->getSynonymsMultiple(array_intersect_key($entities, $entity_ids));
    foreach ($entity_ids as $entity_id => $label) {
      $options[$entity_id] = $label;
      foreach ($synonyms[$entity_id] as $synonym) {
        $options[$entity_id . self::DELIMITER . $synonym['synonym']] = $synonym['wording'];
      }
    }
  }
  $element['#options'] = $options;
  return $element;
}