You are here

public function SaveSearch::build in Search API Saved Searches 8

Builds and returns the renderable array for this block plugin.

If a block should not be rendered because it has no content, then this method must also ensure to return no content: it must then only return an empty array, or an empty array with #cache set (with cacheability metadata indicating the circumstances for it being empty).

Return value

array A renderable array representing the content of the block.

Overrides BlockPluginInterface::build

See also

\Drupal\block\BlockViewBuilder

File

src/Plugin/Block/SaveSearch.php, line 219

Class

SaveSearch
Displays the "Save search" form in a block.

Namespace

Drupal\search_api_saved_searches\Plugin\Block

Code

public function build() {
  $build = [];
  $cacheability = new CacheableMetadata();

  // @todo Move those checks to access()? Would mean access results can't be
  //   cached, though.
  $type = $this
    ->getSavedSearchType();
  if (!$type) {
    $tags = $this
      ->getEntityTypeManager()
      ->getDefinition('search_api_saved_search_type')
      ->getListCacheTags();
    $cacheability
      ->addCacheTags($tags);
    $cacheability
      ->applyTo($build);
    return $build;
  }
  $cacheability
    ->addCacheableDependency($type);
  if (!$type
    ->status()) {
    $cacheability
      ->applyTo($build);
    return $build;
  }

  // Since there is no cache context for "search query on this page", we can't
  // cache this block (unless building it didn't get this far).
  $cacheability
    ->setCacheMaxAge(0);
  $cacheability
    ->applyTo($build);
  $query = $type
    ->getActiveQuery($this
    ->getQueryHelper());
  if (!$query) {
    return $build;
  }
  $description = $type
    ->getOption('description');
  if ($description) {
    $build['description']['#markup'] = Xss::filterAdmin($description);
  }
  $values = [
    'type' => $type
      ->id(),
    'index_id' => $query
      ->getIndex()
      ->id(),
    'query' => $query,
    // Remember the page on which the search was created.
    'path' => $this
      ->getCurrentPath(),
  ];
  $saved_search = $this
    ->getEntityTypeManager()
    ->getStorage('search_api_saved_search')
    ->create($values);
  $form_object = $this
    ->getEntityTypeManager()
    ->getFormObject('search_api_saved_search', 'create');
  $form_object
    ->setEntity($saved_search);
  $build['form'] = $this
    ->getFormBuilder()
    ->getForm($form_object);
  return $build;
}