public function WebformElementController::autocomplete in Webform 8.5
Same name and namespace in other branches
- 6.x src/Controller/WebformElementController.php \Drupal\webform\Controller\WebformElementController::autocomplete()
Returns response for the element autocomplete route.
Parameters
\Symfony\Component\HttpFoundation\Request $request: The current request object containing the search string.
\Drupal\webform\WebformInterface $webform: A webform.
string $key: Webform element key.
Return value
\Symfony\Component\HttpFoundation\JsonResponse A JSON response containing the autocomplete suggestions.
1 string reference to 'WebformElementController::autocomplete'
File
- src/
Controller/ WebformElementController.php, line 56
Class
- WebformElementController
- Provides route responses for Webform elements.
Namespace
Drupal\webform\ControllerCode
public function autocomplete(Request $request, WebformInterface $webform, $key) {
// Get autocomplete query.
$q = $request->query
->get('q') ?: '';
if ($q === '') {
return new JsonResponse([]);
}
// Get the initialized webform element.
$element = $webform
->getElement($key);
if (!$element) {
return new JsonResponse([]);
}
// Set default autocomplete properties.
$element += [
'#autocomplete_existing' => FALSE,
'#autocomplete_items' => [],
'#autocomplete_match' => 3,
'#autocomplete_limit' => 10,
'#autocomplete_match_operator' => 'CONTAINS',
];
// Check minimum number of characters.
if (mb_strlen($q) < (int) $element['#autocomplete_match']) {
return new JsonResponse([]);
}
$matches = [];
// Get existing matches.
if (!empty($element['#autocomplete_existing'])) {
$matches += $this
->getMatchesFromExistingValues($q, $webform
->id(), $key, $element['#autocomplete_match_operator'], $element['#autocomplete_limit']);
}
// Get items (aka options) matches.
if (!empty($element['#autocomplete_items'])) {
$element['#options'] = $element['#autocomplete_items'];
$options = WebformOptions::getElementOptions($element);
$matches += $this
->getMatchesFromOptions($q, $options, $element['#autocomplete_match_operator'], $element['#autocomplete_limit']);
}
// Sort matches by label and enforce the limit.
if ($matches) {
uasort($matches, function (array $a, array $b) {
return $a['label'] > $b['label'];
});
$matches = array_values($matches);
$matches = array_slice($matches, 0, $element['#autocomplete_limit']);
}
return new JsonResponse($matches);
}