You are here

public function WebformImageSelectImagesController::autocomplete in Webform 8.5

Same name and namespace in other branches
  1. 6.x modules/webform_image_select/src/Controller/WebformImageSelectImagesController.php \Drupal\webform_image_select\Controller\WebformImageSelectImagesController::autocomplete()

Returns response for the webform image select images autocompletion.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The current request object containing the search string.

Return value

\Symfony\Component\HttpFoundation\JsonResponse A JSON response containing the autocomplete suggestions.

1 string reference to 'WebformImageSelectImagesController::autocomplete'
webform_image_select.routing.yml in modules/webform_image_select/webform_image_select.routing.yml
modules/webform_image_select/webform_image_select.routing.yml

File

modules/webform_image_select/src/Controller/WebformImageSelectImagesController.php, line 24

Class

WebformImageSelectImagesController
Provides route responses for webform images options.

Namespace

Drupal\webform_image_select\Controller

Code

public function autocomplete(Request $request) {
  $q = $request->query
    ->get('q');
  $webform_images_storage = $this
    ->entityTypeManager()
    ->getStorage('webform_image_select_images');
  $query = $webform_images_storage
    ->getQuery()
    ->range(0, 10)
    ->sort('label');

  // Query title and id.
  $or = $query
    ->orConditionGroup()
    ->condition('id', $q, 'CONTAINS')
    ->condition('label', $q, 'CONTAINS');
  $query
    ->condition($or);
  $entity_ids = $query
    ->execute();
  if (empty($entity_ids)) {
    return new JsonResponse([]);
  }
  $webform_images = $webform_images_storage
    ->loadMultiple($entity_ids);
  $matches = [];
  foreach ($webform_images as $webform_image) {
    $value = new FormattableMarkup('@label (@id)', [
      '@label' => $webform_image
        ->label(),
      '@id' => $webform_image
        ->id(),
    ]);
    $matches[] = [
      'value' => $value,
      'label' => $value,
    ];
  }
  return new JsonResponse($matches);
}