You are here

public static function Reference::autocomplete in FileField Sources 8

Menu callback; autocomplete.js callback to return a list of files.

File

src/Plugin/FilefieldSource/Reference.php, line 129

Class

Reference
A FileField source plugin to allow referencing of existing files.

Namespace

Drupal\filefield_sources\Plugin\FilefieldSource

Code

public static function autocomplete(Request $request, $entity_type, $bundle_name, $field_name) {
  $matches = [];
  $string = mb_strtolower($request->query
    ->get('q'));
  if (isset($string)) {
    $widget = \Drupal::service('entity_display.repository')
      ->getFormDisplay($entity_type, $bundle_name, 'default')
      ->getComponent($field_name);
    if ($widget) {

      // // If we are looking at a single field, cache its settings, in case we want to search all fields.
      $setting_autocomplete = $widget['third_party_settings']['filefield_sources']['filefield_sources']['source_reference']['autocomplete'];
      $setting_search_all_fields = $widget['third_party_settings']['filefield_sources']['filefield_sources']['source_reference']['search_all_fields'];
    }
    $field_definition = \Drupal::entityTypeManager()
      ->getStorage('field_config')
      ->load($entity_type . '.' . $bundle_name . '.' . $field_name);
    if (!isset($field_definition) || $setting_search_all_fields) {
      $field_definitions = \Drupal::entityTypeManager()
        ->getStorage('field_config')
        ->loadByProperties([
        'type' => [
          'file',
          'image',
        ],
      ]);
    }
    else {
      $field_definitions = [
        $field_definition,
      ];
    }
    foreach ($field_definitions as $field_definition) {
      $handler = \Drupal::getContainer()
        ->get('plugin.manager.entity_reference_selection')
        ->getSelectionHandler($field_definition);

      // If we are searching all fields, use the autocomplete settings from the source field.
      $match_operator = empty($setting_autocomplete) ? 'STARTS_WITH' : 'CONTAINS';

      // Get an array of matching entities.
      $entity_labels = $handler
        ->getReferenceableEntities($string, $match_operator, 10);

      // Loop through the entities and convert them into autocomplete output.
      foreach ($entity_labels as $values) {
        foreach ($values as $entity_id => $label) {
          $key = "{$label} [fid:{$entity_id}]";

          // Strip things like starting/trailing white spaces, line breaks and
          // tags.
          $key = preg_replace('/\\s\\s+/', ' ', str_replace("\n", '', trim(Html::decodeEntities(strip_tags($key)))));

          // Names containing commas or quotes must be wrapped in quotes.
          $matches[] = [
            'value' => $key,
            'label' => $label,
          ];
        }
      }
    }
  }
  return new JsonResponse($matches);
}