SearchApiAutocomplete.php in Search API Autocomplete 8
File
src/Element/SearchApiAutocomplete.php
View source
<?php
namespace Drupal\search_api_autocomplete\Element;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Render\Element\Textfield;
use Drupal\search_api_autocomplete\Entity\Search;
class SearchApiAutocomplete extends Textfield {
public function getInfo() {
$info = parent::getInfo();
$class = get_class($this);
$info['#search_id'] = NULL;
$info['#data'] = [];
array_unshift($info['#process'], [
$class,
'processSearchApiAutocomplete',
]);
return $info;
}
public static function processSearchApiAutocomplete(array &$element, FormStateInterface $form_state, array &$complete_form) {
if (empty($element['#search_id'])) {
throw new \InvalidArgumentException('Missing required "#search_id" parameter.');
}
$search = Search::load($element['#search_id']);
if (!$search) {
$search_id = $element['#search_id'];
throw new \InvalidArgumentException("Search entity with ID \"{$search_id}\" not found.");
}
$access = \Drupal::getContainer()
->get('search_api_autocomplete.helper')
->access($search, \Drupal::currentUser());
$metadata = BubbleableMetadata::createFromRenderArray($element);
$metadata
->merge(BubbleableMetadata::createFromObject($access))
->applyTo($element);
if (!$access
->isAllowed()) {
return $element;
}
$options = $search
->getOptions();
$js_settings = [];
if ($options['submit_button_selector'] != ':submit') {
$js_settings['selector'] = $options['submit_button_selector'];
}
$delay = $search
->getOption('delay');
if ($delay !== NULL) {
$js_settings['delay'] = $delay;
}
if ($options['autosubmit']) {
$js_settings['auto_submit'] = TRUE;
}
if ($options['min_length'] > 1) {
$js_settings['min_length'] = $options['min_length'];
}
$element['#attached']['library'][] = 'search_api_autocomplete/search_api_autocomplete';
if ($js_settings) {
$element['#attached']['drupalSettings'] = [
'search_api_autocomplete' => [
$search
->id() => $js_settings,
],
];
}
$element['#autocomplete_route_name'] = 'search_api_autocomplete.autocomplete';
$element['#autocomplete_route_parameters'] = [
'search_api_autocomplete_search' => $search
->id(),
];
if (!empty($element['#additional_data'])) {
$element['#autocomplete_route_parameters'] += $element['#additional_data'];
}
$element['#attributes']['data-search-api-autocomplete-search'] = $search
->id();
foreach ($search
->getSuggesters() as $suggester) {
$suggester
->alterAutocompleteElement($element);
}
return $element;
}
}