invokeAll facets_post_build_facet in order to set a default for language facet

Created on 31 July 2025, 9 days ago

Problem/Motivation

For whatever reason the EventSubscribers just didn't fully function as expected.

Amazingly adding a hook right after one of the event dispatches results in a hook that works well.

Here's the patch code:

diff --git a/src/FacetManager/DefaultFacetManager.php b/src/FacetManager/DefaultFacetManager.php
index 3cf2d03..03060ae 100644
--- a/src/FacetManager/DefaultFacetManager.php
+++ b/src/FacetManager/DefaultFacetManager.php
@@ -375,6 +375,9 @@ class DefaultFacetManager {
       $event = new PostBuildFacet($facet);
       $eventDispatcher->dispatch($event);
 
+      // Call procedural hook to allow module-based preselection or changes.
+      \Drupal::moduleHandler()->invokeAll('facets_post_build_facet', [$facet]);
+
       $this->builtFacets[$facet->getFacetSourceId()][$facet->id()] = $event->getFacet();
     }

and here's the example of my hook that does something useful:

/**
 * Implements hook_facets_post_build_facet().
 */
function mymodule_facets_post_build_facet(\Drupal\facets\FacetInterface $facet) {
  if ($facet->getFieldIdentifier() !== 'language' && $facet->getFieldIdentifier() !== 'langcode') {
    return;
  }

  $params = \Drupal::request()->query->all();
  $hasLanguage = FALSE;

  foreach ($params as $group) {
    if (is_array($group)) {
      foreach ($group as $value) {
        if (is_string($value) && str_starts_with($value, 'language:')) {
          $hasLanguage = TRUE;
          break 2;
        }
      }
    }
  }

  if (!$hasLanguage) {
    $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
    foreach ($facet->getResults() as $result) {
      if ($result->getRawValue() === $langcode) {
        $result->setActiveState(TRUE);
      }
    }
  }
}

Steps to reproduce

add two or more languages, add and translate content, add a language facet.

Proposed resolution

See patch/merge request.

Remaining tasks

TBD

User interface changes

See issue description

API changes

Yes

Data model changes

N/A

✨ Feature request
Status

Needs work

Version

3.0

Component

Code

Created by

πŸ‡¨πŸ‡¦Canada joseph.olstad

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024