public function TranslateEntityProcessor::build in Facets 8
Runs before the renderable array is created.
Parameters
\Drupal\facets\FacetInterface $facet: The facet being changed.
\Drupal\facets\Result\ResultInterface[] $results: The results being changed.
Return value
\Drupal\facets\Result\ResultInterface[] The changed results.
Overrides BuildProcessorInterface::build
File
- src/
Plugin/ facets/ processor/ TranslateEntityProcessor.php, line 82
Class
- TranslateEntityProcessor
- Transforms the results to show the translated entity label.
Namespace
Drupal\facets\Plugin\facets\processorCode
public function build(FacetInterface $facet, array $results) {
$language_interface = $this->languageManager
->getCurrentLanguage();
/** @var \Drupal\Core\TypedData\DataDefinitionInterface $data_definition */
$data_definition = $facet
->getDataDefinition();
$property = NULL;
foreach ($data_definition
->getPropertyDefinitions() as $k => $definition) {
if ($definition instanceof DataReferenceDefinitionInterface) {
$property = $k;
break;
}
}
if ($property === NULL) {
throw new InvalidProcessorException("Field doesn't have an entity definition, so this processor doesn't work.");
}
$entity_type = $data_definition
->getPropertyDefinition($property)
->getTargetDefinition()
->getEntityTypeId();
/** @var \Drupal\facets\Result\ResultInterface $result */
$ids = [];
foreach ($results as $delta => $result) {
$ids[$delta] = $result
->getRawValue();
}
// Load all indexed entities of this type.
$entities = $this->entityTypeManager
->getStorage($entity_type)
->loadMultiple($ids);
// Loop over all results.
foreach ($results as $i => $result) {
if (!isset($entities[$ids[$i]])) {
unset($results[$i]);
continue;
}
/** @var \Drupal\Core\Entity\ContentEntityBase $entity */
$entity = $entities[$ids[$i]];
// Check for a translation of the entity and load that instead if one's
// found.
if ($entity instanceof TranslatableInterface && $entity
->hasTranslation($language_interface
->getId())) {
$entity = $entity
->getTranslation($language_interface
->getId());
}
// Overwrite the result's display value.
$results[$i]
->setDisplayValue($entity
->label());
}
// Return the results with the new display values.
return $results;
}