CustomScript.php in Search API Autocomplete 8
File
src/Plugin/search_api_autocomplete/suggester/CustomScript.php
View source
<?php
namespace Drupal\search_api_autocomplete\Plugin\search_api_autocomplete\suggester;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Url;
use Drupal\search_api\Plugin\PluginFormTrait;
use Drupal\search_api\Query\QueryInterface;
use Drupal\search_api_autocomplete\SearchInterface;
use Drupal\search_api_autocomplete\Suggester\SuggesterPluginBase;
class CustomScript extends SuggesterPluginBase implements PluginFormInterface {
use PluginFormTrait;
public static function supportsSearch(SearchInterface $search) {
return (bool) \Drupal::config('search_api_autocomplete.settings')
->get('enable_custom_scripts');
}
public function defaultConfiguration() {
return [
'path' => '',
];
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['path'] = [
'#type' => 'textfield',
'#title' => $this
->t('Custom script path'),
'#description' => $this
->t('The internal path or external URL to use for autocompletion. A local path should start with a leading slash. For using an external URL, please take CSRF protection into account.'),
'#default_value' => $this->configuration['path'],
];
return $form;
}
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
if ($form_state
->getValue('path', '') === '') {
$args = [
'%field' => $form['path']['#title'],
];
$message = $this
->t('The %field field is required.', $args);
$form_state
->setError($form['path'], $message);
}
}
public function alterAutocompleteElement(array &$element) {
$options['query'] = $element['#autocomplete_route_parameters'];
unset($element['#autocomplete_route_name'], $element['#autocomplete_route_parameters']);
$path = $this->configuration['path'];
$path_len = strlen($path);
if ($path_len > 1 && $path[0] === '/' && ($path_len < 2 || $path[1] !== '/')) {
$url = Url::fromUserInput($path, $options);
}
else {
$url = Url::fromUri($path, $options);
}
$url = $url
->toString(TRUE);
$element['#attributes']['class'][] = 'form-autocomplete';
$element['#attributes']['data-autocomplete-path'] = $url
->getGeneratedUrl();
$metadata = BubbleableMetadata::createFromRenderArray($element);
$metadata
->merge($url)
->applyTo($element);
}
public function getAutocompleteSuggestions(QueryInterface $query, $incomplete_key, $user_input) {
return [];
}
}
Classes
Name |
Description |
CustomScript |
Uses a custom (non-Drupal) script for generating autocomplete suggestions. |