You are here

GridStackEntityFormatterBase.php in GridStack 8.2

Same filename and directory in other branches
  1. 8 src/Plugin/Field/FieldFormatter/GridStackEntityFormatterBase.php

File

src/Plugin/Field/FieldFormatter/GridStackEntityFormatterBase.php
View source
<?php

namespace Drupal\gridstack\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\blazy\Dejavu\BlazyEntityBase;
use Drupal\gridstack\GridStackDefault;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Base class for gridstack entity reference formatters without field details.
 */
abstract class GridStackEntityFormatterBase extends BlazyEntityBase {
  use GridStackFormatterTrait {
    buildSettings as traitBuildSettings;
  }
  use GridStackFormatterViewTrait;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    return self::injectServices($instance, $container, 'entity');
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    $settings = GridStackDefault::baseSettings();
    $settings['view_mode'] = '';
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function buildElement(array &$build, $entity, $langcode) {
    $view_mode = empty($build['settings']['view_mode']) ? 'full' : $build['settings']['view_mode'];
    $delta = $build['settings']['delta'];

    // Adds element box to contain any entity as expected by GridStackManager.
    $build['items'][$delta] = [
      'box' => $this
        ->formatter()
        ->getEntityTypeManager()
        ->getViewBuilder($entity
        ->getEntityTypeId())
        ->view($entity, $view_mode, $langcode),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $entities = $this
      ->getEntitiesToView($items, $langcode);

    // Early opt-out if the field is empty.
    if (empty($entities)) {
      return [];
    }
    return $this
      ->commonViewElements($items, $langcode, $entities);
  }

  /**
   * Builds the settings.
   */
  public function buildSettings() {
    return [
      'vanilla' => TRUE,
    ] + $this
      ->traitBuildSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function getScopedFormElements() {
    return $this
      ->getCommonScopedFormElements() + parent::getScopedFormElements();
  }

}

Classes

Namesort descending Description
GridStackEntityFormatterBase Base class for gridstack entity reference formatters without field details.