Created
June 25, 2018 19:04
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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