drafted ajax search call

This commit is contained in:
2019-06-01 16:15:08 +02:00
parent d21bd5ef4e
commit 7f65fd79a4
9 changed files with 278 additions and 17 deletions

View File

@@ -0,0 +1,97 @@
<?php
// https://www.qed42.com/blog/autocomplete-drupal-8
// https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code
namespace Drupal\materio_sapi\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Utility\Tags;
use Drupal\Component\Utility\Unicode;
use Drupal\search_api\Entity\Index;
// https://drupal.stackexchange.com/questions/225008/programatically-use-search-api
/**
* Defines a route controller for entity autocomplete form elements.
*/
class Base extends ControllerBase {
/**
* Handler for autocomplete request.
*/
public function getResults(Request $request) {
$resp = [
'tes' => 'ok',
'autocomplete' => $request->query->get('autocomplete'),
'keys' => $request->query->get('keys'),
'range' => array(
'offset' => $request->query->get('offset'),
'limit' => $request->query->get('limit'),
),
];
// Get the typed string from the URL, if it exists.
if ($keys = $resp['keys']) {
$typed_string = Tags::explode($keys);
$typed_string = Unicode::strtolower($keys);
\Drupal::logger('materio_sapi')->notice($typed_string);
$index = Index::load('database');
$query = $index->query();
// Change the parse mode for the search.
$parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
->createInstance('direct');
$parse_mode->setConjunction('OR');
$query->setParseMode($parse_mode);
// Set fulltext search keywords and fields.
$query->keys($typed_string);
// $query->setFulltextFields(['name']);
// Set additional conditions.
// $query->addCondition('status', 1)
// ->addCondition('author', 1, '<>');
// Restrict the search to specific languages.
// $query->setLanguages(['de', 'it']);
// Do paging.
$query->range($resp['range']['offset'], $resp['range']['limit']);
// Add sorting.
$query->sort('search_api_relevance', 'DESC');
// Set one or more tags for the query.
// @see hook_search_api_query_TAG_alter()
// @see hook_search_api_results_TAG_alter()
$query->addTag('materio_sapi_search');
$results = $query->execute();
$resultitems = $results->getResultItems();
$resp['count'] = $results->getResultCount();
$resp['resultitems'] = array_keys($resultitems);
$resp['options'] = $query->getOptions();
$items = [];
foreach ($results as $result) {
// \Drupal::logger('materio_sapi')->notice(print_r($result->getField('tid')->getValues(),true));
// \Drupal::logger('materio_sapi')->notice(print_r($result->getField('name')->getValues(),true));
$nid = $result->getField('nid')->getValues()[0];
$title = $result->getField('title')->getValues()[0]->getText();
$items[] = [
'nid' => $nid,
'title' => $title,
];
}
$resp['items'] = $items;
}
return new JsonResponse($resp);
}
}