0

I want to use an autocomplete input field for the global search on my Drupal 9 page. But instead of listing term suggestions to show what the user might search I use a custom controller and a search api view to find and display the matching result nodes as "autocomplete" results. So in the step after getting the results from my search api view by

$view = Views::getView('search_content');
if (is_object($view)) {
  $view->setArguments($args);
  $view->setDisplay('autocomplete');
  $view->execute();
}

I want to return all these results to the JavaScript function of the tomickigrzegorz/autocomplete module. I have to place every result into my array $matches['label' and return it as a JSON object. The receiving JavaScript function will map every element and place it into a <li> element. Until here my code works properly.

My question is: Can I render my view result rows (using the appropriate view mode defined in the view row settings) in my php controller like I can render the whole view by doing

$rendered = $view->render();
$output = \Drupal::service('renderer')->render($rendered);

I found serveral tips but could only find some for Drupal 7.

4
  • Off the top of my head, if the JS is expecting a JSON response, you need to return a JsonResponse object from the controller in Drupal back to JS formatted as a JSON object that the JS library expects to receive.
    – Kevin
    Commented Sep 9 at 13:53
  • In fact, thinking about it more, the View could be a REST Export and serialized for you instead of a regular View.
    – Kevin
    Commented Sep 9 at 14:00
  • The JSON response and the whole process is not my problem. I would like to render every single view result row. But I don't know if and how this is still possible from drupal 8 on.
    – henrik23
    Commented Sep 10 at 4:23
  • Thanks, Kevin. REST export is a good idea for the next project. This time I built my own template rendering class and method in my custom module. So my problem is solved.
    – henrik23
    Commented Sep 17 at 12:05

1 Answer 1

-1

You can add a custom event to the autocomplete method in JavaScript. Maybe you can go this way. Here is an example (near line 79): https://git.drupalcode.org/project/permissions_by_term/-/blob/3.1.x-dev/js/src/drupal-behavior-function/node-form-client.js?ref_type=heads

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.