Skip to content

Instantly share code, notes, and snippets.

@kevinquillen
Created June 25, 2018 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinquillen/8bb78f56c10703211e2e999bc569a509 to your computer and use it in GitHub Desktop.
Save kevinquillen/8bb78f56c10703211e2e999bc569a509 to your computer and use it in GitHub Desktop.
This field formatter can be used on entity reference fields to select a random entity from the list to render. Note that the more items you have, the better the 'random' pick will seem. Also note that this will only fire once per cache write, then again on cache clear.
<?php
namespace Drupal\harlib_random_entity_display\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceEntityFormatter;
/**
* Plugin implementation of the 'random_entity_field_formatter' formatter.
*
* @FieldFormatter(
* id = "random_entity_field_formatter",
* label = @Translation("Random rendered entity"),
* field_types = {
* "entity_reference"
* }
* )
*/
final class RandomEntityFieldFormatter extends EntityReferenceEntityFormatter {
public function settingsSummary() {
$summary = [];
$view_modes = $this->entityDisplayRepository->getViewModeOptions($this->getFieldSetting('target_type'));
$view_mode = $this->getSetting('view_mode');
$summary[] = $this->t('Randomly selected entity will be rendered.');
$summary[] = $this->t('Rendered as @mode', ['@mode' => isset($view_modes[$view_mode]) ? $view_modes[$view_mode] : $view_mode]);
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$view_mode = $this->getSetting('view_mode');
$elements = [];
$all = $this->getEntitiesToView($items, $langcode);
if (count($all)) {
$entity = $all[array_rand($all, 1)];
$view_builder = $this->entityTypeManager->getViewBuilder($entity->getEntityTypeId());
$elements[] = $view_builder->view($entity, $view_mode, $entity->language()
->getId());
}
return $elements;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment