improvements-2.x-dev/modules/improvements_views/src/Plugin/Field/FieldFormatter/EntityReferenceViewsFormatter.php
modules/improvements_views/src/Plugin/Field/FieldFormatter/EntityReferenceViewsFormatter.php
<?php namespace Drupal\improvements_views\Plugin\Field\FieldFormatter; use Drupal\Core\Field\FieldItemInterface; use Drupal\Core\Field\FieldItemListInterface; use Drupal\Core\Field\FormatterBase; use Drupal\Core\Form\FormStateInterface; use Drupal\views\Views; /** * @FieldFormatter( * id = "entity_reference_views_formatter", * label = @Translation("Views"), * field_types = { * "entity_reference", * }, * ) */ class EntityReferenceViewsFormatter extends FormatterBase { /** * {@inheritdoc} */ public static function defaultSettings(): array { return [ 'views' => '', ] + parent::defaultSettings(); } /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state): array { $elements['views'] = [ '#title' => t('Views'), '#type' => 'select', '#default_value' => $this->getSetting('view_name'), '#options' => Views::getViewsAsOptions(FALSE, 'enabled', NULL, FALSE, TRUE), '#required' => TRUE, ]; return $elements; } /** * {@inheritDoc} */ public function settingsSummary(): array { $summary[] = t('Views') . ': ' . ($this->getSetting('views') ?: t('none')); return $summary; } /** * {@inheritDoc} */ public function viewElements(FieldItemListInterface $items, $langcode): ?array { if ($views_key = $this->getSetting('views')) { [$view_id, $view_display_name] = explode(':', $views_key); $target_ids = array_map(fn(FieldItemInterface $item) => $item->target_id, iterator_to_array($items)); return $target_ids ? [views_embed_view($view_id, $view_display_name, implode('+', $target_ids))] : []; } return NULL; } }