public function YamlFormElementController::autocomplete in YAML Form 8
Returns response for the element autocomplete route.
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.
1 string reference to 'YamlFormElementController::autocomplete'
File
- src/
Controller/ YamlFormElementController.php, line 57
Class
- YamlFormElementController
- Provides route responses for form element.
Namespace
Drupal\yamlform\ControllerCode
public function autocomplete(Request $request, YamlFormInterface $yamlform, $key) {
// Get autocomplete query.
$q = $request->query
->get('q') ?: '';
if ($q == '') {
return new JsonResponse([]);
}
// Get the initialized form element.
$element = $yamlform
->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 (Unicode::strlen($q) < (int) $element['#autocomplete_match']) {
return new JsonResponse([]);
}
$matches = [];
// Get existing matches.
if (!empty($element['#autocomplete_existing'])) {
$matches += $this
->getMatchesFromExistingValues($q, $yamlform
->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 = YamlFormOptions::getElementOptions($element);
$matches += $this
->getMatchesFromOptions($q, $options, $element['#autocomplete_match_operator'], $element['#autocomplete_limit']);
}
// Sort matches and enforce the limit.
if ($matches) {
ksort($matches);
$matches = array_values($matches);
$matches = array_slice($matches, 0, $element['#autocomplete_limit']);
}
return new JsonResponse($matches);
}