You are here

public function YamlFormController::autocomplete in YAML Form 8

Returns a form filter form autocomplete matches.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The current request.

bool $templates: If TRUE, limit autocomplete matches to form templates.

Return value

\Symfony\Component\HttpFoundation\JsonResponse The JSON response.

2 string references to 'YamlFormController::autocomplete'
yamlform.routing.yml in ./yamlform.routing.yml
yamlform.routing.yml
yamlform_templates.routing.yml in modules/yamlform_templates/yamlform_templates.routing.yml
modules/yamlform_templates/yamlform_templates.routing.yml

File

src/Controller/YamlFormController.php, line 142

Class

YamlFormController
Provides route responses for form.

Namespace

Drupal\yamlform\Controller

Code

public function autocomplete(Request $request, $templates = FALSE) {
  $q = $request->query
    ->get('q');
  $yamlform_storage = $this
    ->entityTypeManager()
    ->getStorage('yamlform');
  $query = $yamlform_storage
    ->getQuery()
    ->condition('title', $q, 'CONTAINS')
    ->range(0, 10)
    ->sort('title');

  // Limit query to templates.
  if ($templates) {
    $query
      ->condition('template', TRUE);
  }
  elseif ($this
    ->moduleHandler()
    ->moduleExists('yamlform_templates')) {

    // Filter out templates if the yamlform_template.module is enabled.
    $query
      ->condition('template', FALSE);
  }
  $entity_ids = $query
    ->execute();
  if (empty($entity_ids)) {
    return new JsonResponse([]);
  }
  $yamlforms = $yamlform_storage
    ->loadMultiple($entity_ids);
  $matches = [];
  foreach ($yamlforms as $yamlform) {
    if ($yamlform
      ->access('view')) {
      $value = new FormattableMarkup('@label (@id)', [
        '@label' => $yamlform
          ->label(),
        '@id' => $yamlform
          ->id(),
      ]);
      $matches[] = [
        'value' => $value,
        'label' => $value,
      ];
    }
  }
  return new JsonResponse($matches);
}