You are here

public function YamlFormOptionsController::autocomplete in YAML Form 8

Returns response for the element autocompletion.

Parameters

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

\Drupal\yamlform\YamlFormInterface $yamlform: A form.

string $key: Form element key.

Return value

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

File

src/Controller/YamlFormOptionsController.php, line 30

Class

YamlFormOptionsController
Provides route responses for form options.

Namespace

Drupal\yamlform\Controller

Code

public function autocomplete(Request $request, YamlFormInterface $yamlform, $key) {
  $q = $request->query
    ->get('q');

  // Make sure the current user can access this form.
  if (!$yamlform
    ->access('view')) {
    return new JsonResponse([]);
  }

  // Get the form element element.
  $elements = $yamlform
    ->getElementsInitializedAndFlattened();
  if (!isset($elements[$key])) {
    return new JsonResponse([]);
  }

  // Get the element's form options.
  $element = $elements[$key];
  $element['#options'] = $element['#autocomplete'];
  $options = YamlFormOptions::getElementOptions($element);
  if (empty($options)) {
    return new JsonResponse([]);
  }

  // Filter and convert options to autocomplete matches.
  $matches = [];
  $this
    ->appendOptionsToMatchesRecursive($q, $options, $matches);
  return new JsonResponse($matches);
}