kevinquillen
9/6/2016 - 4:58 PM

Example of a Controller using SearchAPI to generate a results page (without Views).

Example of a Controller using SearchAPI to generate a results page (without Views).

<?php

namespace Drupal\velirsearch\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\velirsearch\Service\PagerService;

class SearchResults extends ControllerBase {

  /**
   * @var \Drupal\velirsearch\Service\PagerService
   */
  private $pager_service;

  /**
   * SearchResults constructor.
   * @param \Drupal\velirsearch\Service\PagerService $pager_service
   */
  public function __construct(PagerService $pager_service) {
    $this->pager_service = $pager_service;
  }

  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @return static
   */
  public static function create(ContainerInterface $container) {
    $pager_service = $container->get('velirsearch.pager_service');
    return new static($pager_service);
  }

  /**
   * @param \Symfony\Component\HttpFoundation\Request $request
   * @return array
   */
  public function build(Request $request) {
    /* @var $search_api_index \Drupal\search_api\IndexInterface */
    $index = $this->getSearchIndex('new_solr_test');

    // Create the query.
    $query = $index->query([
      'limit' => 10,
      'offset' => !is_null($request->get('page')) ? $request->get('page') * 10 : 0,
      'search id' => 'velirsearch:1',
    ]);

    if (!is_null($request->get('keyword'))) {
      $query->keys(['body' => $request->get('keyword'), '#conjunction' => 'AND']);
    }

    $results = $query->execute();

    $output = '';

    foreach ($results as $result) {
      $value = $result->getField('view_mode_teaser')->getValues();
      $output .= $value[0];
    }

    $render[] = [
      '#markup' => $output,
      '#type' => 'remote',
    ];

    $render[] = $this->attachPager($results->getResultCount(), 10);

    return $render;
  }

  /**
   * Title callback.
   *
   * @param Request $request
   *   The request.
   *
   * @return string $title
   *   The page title.
   */
  public function title(Request $request) {
    if (!is_null($request->get('keyword'))) {
      return $this->t('Search results for %keyword', ['%keyword' => $request->get('keyword')]);
    }

    return $this->t('Search results');
  }

  /**
   * Load and return a search index.
   * @param $id
   * @return \Drupal\Core\Entity\EntityInterface|null
   */
  protected function getSearchIndex($id) {
    return $this->entityTypeManager()->getStorage('search_api_index')->load($id);
  }

  /**
   * Convenient method to obtain a pager to attach from the pager service.
   * @param $totalRows
   * @param $limit
   * @return array
   */
  protected function attachPager($totalRows, $limit) {
    return $this->pager_service->getPager($totalRows, $limit);
  }
}