Quick tip: Working with facets directly in D8

Published

There are some cases where you want to interact with Facets on a Search API page, apart from just rendering them.

The API for facets in D8 provides you with services to make that easily possible, however, there aren't many examples out there yet for cases such as these where you work outside the primary rendering pipeline. The trick is to process the facet not build it, to get at the actual data:

/** @var \Drupal\facets\FacetManager\DefaultFacetManager $manager */
$manager = Drupal::service('facets.manager');
/** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
$storage = Drupal::service('entity_type.manager')
  ->getStorage('facets_facet');
/** @var \Drupal\facets\Entity\facet $facet */
$facet = $storage->load('my_facet');
$processed_facet = $manager->returnProcessedFacet($facet);

From here on out working with the facet is trivial and straightfoward, e.g.:

results = $processed_facet->getResults();

$topics = array();
foreach ($results as $result) {
  if ($result->isActive()) {
    $topics[] = $result->getRawValue();
  }
}