Programmatically render a facet

Posted by patrick on Wed, 03/08/2017 - 08:47

If you want to programmatically render a facet block provided by the Facets module, for example to provide a variable in a preprocess function, it would look something like this:

use Drupal\Component\Plugin\PluginBase;
 
$facet = 'your_facet_id';
$render = [];
$block_manager = \Drupal::service('plugin.manager.block');
$config = [];
$block_plugin = $block_manager->createInstance('facet_block' . PluginBase::DERIVATIVE_SEPARATOR . $facet, $config);
if ($block_plugin) {
  $access_result = $block_plugin->access(\Drupal::currentUser());
  if ($access_result) {
    $render = $block_plugin->build();
  }
}
if (count($render) > 0) {
  $language_manager = \Drupal::service('language_manager');
  $lang_code = $language_manager->getCurrentLanguage()->getId();
  $translated_label = $language_manager->getLanguageConfigOverride($lang_code, 'facets.facet.' . $facet)->get('name');
  $variables[$facet] = [
    'title' => $translated_label ? $translated_label : $block_plugin->label(),
    'render' => $render,
  ];
}

First, you would need the facet id. The facet id is the machine name you provided when you added the facet. If you don't remember the machine name, you could look at the available configuration (Facets will store its configuration as facets.facet.<id>) or at the edit URL of the facet on the facets configuration page (admin/config/search/facets/<id>/edit). Then we'll get the BlockManager and create an instance of the facet block. Since the current user might not have access to the facet block, we'll check for that, just to be sure, and then we'll build the plugin. If the facet is not empty, we'll get the translated label from facet configuration, if any, and provide the result as a renderable array to our template.

Systems
Drupal 8/9