You are here

class SynonymsEntityAutocomplete in Synonyms 8

Form element for synonyms-friendly entity autocomplete.

Plugin annotation

@FormElement("synonyms_entity_autocomplete");

Hierarchy

Expanded class hierarchy of SynonymsEntityAutocomplete

2 #type uses of SynonymsEntityAutocomplete
EntityReferenceSynonymsAutocomplete::formElement in src/Plugin/Field/FieldWidget/EntityReferenceSynonymsAutocomplete.php
Returns the form for a single field widget.
SynonymsEntity::valueForm in synonyms_views_filter/src/Plugin/views/filter/SynonymsEntity.php
Options form subform for setting options.

File

src/Element/SynonymsEntityAutocomplete.php, line 16

Namespace

Drupal\synonyms\Element
View source
class SynonymsEntityAutocomplete extends Textfield {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $info = parent::getInfo();

    // Target entity type for suggestions.
    $info['#target_type'] = NULL;

    // String or array of allowed target bundles. If omitted, all bundles will
    // be included in autocomplete suggestions.
    $info['#target_bundles'] = NULL;

    // Default maximum amount of provided suggestions.
    $info['#suggestion_size'] = 10;

    // Whether to suggest same entity at most once (in the case, when more than
    // 1 synonym triggers inclusion of that entity).
    $info['#suggest_only_unique'] = FALSE;

    // Operator to match keyword. Allowed values are:
    // - CONTAINS
    // - STARTS_WITH.
    $info['#match'] = 'CONTAINS';
    array_unshift($info['#process'], [
      get_class($this),
      'elementSynonymsEntityAutocomplete',
    ]);
    $info['#element_validate'][] = [
      get_class($this),
      'validateEntityAutocomplete',
    ];
    return $info;
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    $entities = NULL;
    if ($input === FALSE) {
      if (isset($element['#default_value'])) {
        $entities = [];
        foreach ($element['#default_value'] as $entity) {
          $entities[] = $entity;
        }
      }
    }
    elseif ($input !== FALSE && is_array($input)) {
      $entity_ids = array_map(function (array $item) {
        return $item['target_id'];
      }, $input);
      $entities = \Drupal::entityTypeManager()
        ->getStorage($element['#target_type'])
        ->loadMultiple($entity_ids);
    }
    if (is_array($entities)) {
      $value = [];
      foreach ($entities as $entity) {
        $value[] = $entity
          ->label() . ' (' . $entity
          ->id() . ')';
      }
      return Tags::implode($value);
    }
  }

  /**
   * Form element process callback for 'synonyms_entity_autocomplete' type.
   */
  public static function elementSynonymsEntityAutocomplete(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $data = [
      'target_type' => $element['#target_type'],
      'target_bundles' => $element['#target_bundles'],
      'suggestion_size' => $element['#suggestion_size'],
      'suggest_only_unique' => $element['#suggest_only_unique'],
      'match' => $element['#match'],
    ];
    $token = Crypt::hmacBase64(serialize($data), Settings::getHashSalt());
    $key_value_storage = \Drupal::keyValue('synonyms_entity_autocomplete');
    $key_value_storage
      ->setIfNotExists($token, $data);
    $element['#autocomplete_route_name'] = 'synonyms.entity_autocomplete';
    $element['#autocomplete_route_parameters'] = [
      'target_type' => $element['#target_type'],
      'token' => $token,
    ];
    return $element;
  }

  /**
   * Form element validation handler for synonyms_entity_autocomplete elements.
   */
  public static function validateEntityAutocomplete(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $tokens = Tags::explode($form_state
      ->getValue($element['#parents']));
    $value = [];
    $autocomplete_service = \Drupal::getContainer()
      ->get('synonyms.behavior.autocomplete');
    foreach ($tokens as $token) {
      $entity_id = self::extractEntityIdFromAutocompleteInput($token);
      if (!$entity_id) {
        $lookup = $autocomplete_service
          ->autocompleteLookup($token, $element['#autocomplete_route_parameters']['token']);
        $lookup = array_shift($lookup);
        if ($lookup) {
          $entity_id = $lookup['entity_id'];
        }
      }
      if ($entity_id) {
        $value[] = [
          'target_id' => $entity_id,
        ];
      }
    }
    $form_state
      ->setValueForElement($element, $value);
  }

  /**
   * Extracts the entity ID from the autocompletion result.
   *
   * @param string $input
   *   The input coming from the autocompletion result.
   *
   * @return mixed|null
   *   The return value
   */
  public static function extractEntityIdFromAutocompleteInput($input) {
    $match = NULL;

    // Take "label (entity id)', match the ID from parenthesis when it's a
    // number.
    if (preg_match("/.+\\s\\((\\d+)\\)/", $input, $matches)) {
      $match = $matches[1];
    }
    return $match;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormElement::processAutocomplete public static function Adds autocomplete functionality to elements.
FormElement::processPattern public static function #process callback for #pattern form element property.
FormElement::validatePattern public static function #element_validate callback for #pattern form element property.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 92
RenderElement::preRenderAjaxForm public static function Adds Ajax information about an element to communicate with JavaScript.
RenderElement::preRenderGroup public static function Adds members of this group as actual elements for rendering.
RenderElement::processAjaxForm public static function Form element processing handler for the #ajax form property. 1
RenderElement::processGroup public static function Arranges elements into groups.
RenderElement::setAttributes public static function Sets a form element's class attribute. Overrides ElementInterface::setAttributes
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
SynonymsEntityAutocomplete::elementSynonymsEntityAutocomplete public static function Form element process callback for 'synonyms_entity_autocomplete' type.
SynonymsEntityAutocomplete::extractEntityIdFromAutocompleteInput public static function Extracts the entity ID from the autocompletion result.
SynonymsEntityAutocomplete::getInfo public function Returns the element properties for this element. Overrides Textfield::getInfo
SynonymsEntityAutocomplete::validateEntityAutocomplete public static function Form element validation handler for synonyms_entity_autocomplete elements.
SynonymsEntityAutocomplete::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides Textfield::valueCallback
Textfield::preRenderTextfield public static function Prepares a #type 'textfield' render element for input.html.twig.