You are here

class EntityField in Chaos Tool Suite (ctools) 8.3

Provides a block to a field on an entity.

Plugin annotation


@Block(
  id = "entity_field",
  deriver = "Drupal\ctools_block\Plugin\Deriver\EntityFieldDeriver",
)

Hierarchy

Expanded class hierarchy of EntityField

File

modules/ctools_block/src/Plugin/Block/EntityField.php, line 28

Namespace

Drupal\ctools_block\Plugin\Block
View source
class EntityField extends BlockBase implements ContextAwarePluginInterface, ContainerFactoryPluginInterface {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The field type manager.
   *
   * @var \Drupal\Core\Field\FieldTypePluginManagerInterface
   */
  protected $fieldTypeManager;

  /**
   * The formatter manager.
   *
   * @var \Drupal\Core\Field\FormatterPluginManager
   */
  protected $formatterManager;

  /**
   * The entity type id.
   *
   * @var string
   */
  protected $entityTypeId;

  /**
   * The field name.
   *
   * @var string
   */
  protected $fieldName;

  /**
   * The field definition.
   *
   * @var \Drupal\Core\Field\FieldDefinitionInterface
   */
  protected $fieldDefinition;

  /**
   * The field storage definition.
   *
   * @var \Drupal\Core\Field\FieldStorageDefinitionInterface
   */
  protected $fieldStorageDefinition;

  /**
   * Constructs a new EntityField.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager.
   * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager
   *   The field type manager.
   * @param \Drupal\Core\Field\FormatterPluginManager $formatter_manager
   *   The formatter manager.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, FieldTypePluginManagerInterface $field_type_manager, FormatterPluginManager $formatter_manager) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFieldManager = $entity_field_manager;
    $this->fieldTypeManager = $field_type_manager;
    $this->formatterManager = $formatter_manager;

    // Get the entity type and field name from the plugin id.
    list(, $entity_type_id, $field_name) = explode(':', $plugin_id);
    $this->entityTypeId = $entity_type_id;
    $this->fieldName = $field_name;
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'), $container
      ->get('plugin.manager.field.field_type'), $container
      ->get('plugin.manager.field.formatter'));
  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    /** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */
    $entity = $this
      ->getContextValue('entity');
    $build = [];

    /** @var \Drupal\Core\Field\FieldItemListInterface $field */
    $field = $entity->{$this->fieldName};
    $display_settings = $this
      ->getConfiguration()['formatter'];
    $build['field'] = $field
      ->view($display_settings);

    // Set the cache data appropriately.
    $build['#cache']['contexts'] = $this
      ->getCacheContexts();
    $build['#cache']['tags'] = $this
      ->getCacheTags();
    $build['#cache']['max-age'] = $this
      ->getCacheMaxAge();
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {

    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $this
      ->getContextValue('entity');

    // Make sure we have access to the entity.
    $access = $entity
      ->access('view', $account, TRUE);
    if ($access
      ->isAllowed()) {

      // Check that the entity in question has this field.
      if ($entity instanceof FieldableEntityInterface && $entity
        ->hasField($this->fieldName)) {

        // Check field access.
        $field_access = $this->entityTypeManager
          ->getAccessControlHandler($this->entityTypeId)
          ->fieldAccess('view', $this
          ->getFieldDefinition(), $account);
        if ($field_access) {

          // Build a renderable array for the field.
          $build = $entity
            ->get($this->fieldName)
            ->view($this->configuration['formatter']);

          // If there are actual renderable children, grant access.
          if (Element::children($build)) {
            return AccessResult::allowed();
          }
        }
      }

      // Entity doesn't have this field, so access is denied.
      return AccessResult::forbidden();
    }

    // If we don't have access to the entity, return the forbidden result.
    return $access;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $field_type_definition = $this
      ->getFieldTypeDefinition();
    return [
      'formatter' => [
        'label' => 'above',
        'type' => isset($field_type_definition['default_formatter']) ? $field_type_definition['default_formatter'] : '',
        'settings' => [],
        'third_party_settings' => [],
        'weight' => 0,
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $config = $this
      ->getConfiguration();
    $form['formatter_label'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Label'),
      '#options' => [
        'above' => $this
          ->t('Above'),
        'inline' => $this
          ->t('Inline'),
        'hidden' => '- ' . $this
          ->t('Hidden') . ' -',
        'visually_hidden' => '- ' . $this
          ->t('Visually Hidden') . ' -',
      ],
      '#default_value' => $config['formatter']['label'],
    ];
    $form['formatter_type'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Formatter'),
      '#options' => $this
        ->getFormatterOptions(),
      '#default_value' => $config['formatter']['type'],
      '#ajax' => [
        'callback' => [
          static::class,
          'formatterSettingsAjaxCallback',
        ],
        'wrapper' => 'formatter-settings-wrapper',
        'effect' => 'fade',
      ],
    ];

    // Add the formatter settings to the form via AJAX.
    $form['#process'][] = [
      $this,
      'formatterSettingsProcessCallback',
    ];
    $form['formatter_settings_wrapper'] = [
      '#prefix' => '<div id="formatter-settings-wrapper">',
      '#suffix' => '</div>',
    ];
    $form['formatter_settings_wrapper']['formatter_settings'] = [
      '#tree' => TRUE,
    ];
    return $form;
  }

  /**
   * Render API callback: builds the formatter settings elements.
   */
  public function formatterSettingsProcessCallback(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $config = $this
      ->getConfiguration();
    $parents_base = $element['#parents'];
    $formatter_parent = array_merge($parents_base, [
      'formatter_type',
    ]);
    $formatter_settings_parent = array_merge($parents_base, [
      'formatter_settings',
    ]);
    $settings_element =& $element['formatter_settings_wrapper']['formatter_settings'];

    // Set the #parents on the formatter_settings so they end up as a peer to
    // formatter_type.
    $settings_element['#parents'] = $formatter_settings_parent;

    // Get the formatter name in a way that works regardless of whether we're
    // getting the value via AJAX or not.
    $formatter_name = NestedArray::getValue($form_state
      ->getUserInput(), $formatter_parent) ?: $element['formatter_type']['#default_value'];

    // Place the formatter settings on the form if a formatter is selected.
    $formatter = $this
      ->getFormatter($formatter_name, $form_state
      ->getValue('formatter_label'), $form_state
      ->getValue($formatter_settings_parent, $config['formatter']['settings']), $config['formatter']['third_party_settings']);
    $settings_element = array_merge($formatter
      ->settingsForm($settings_element, $form_state), $settings_element);

    // Store the array parents for our element so that we can use it to pull out
    // the formatter settings in our AJAX callback.
    $complete_form['#formatter_array_parents'] = $element['#array_parents'];
    return $element;
  }

  /**
   * Render API callback: gets the layout settings elements.
   */
  public static function formatterSettingsAjaxCallback(array $form, FormStateInterface $form_state) {
    $formatter_array_parents = $form['#formatter_array_parents'];
    return NestedArray::getValue($form, array_merge($formatter_array_parents, [
      'formatter_settings_wrapper',
    ]));
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['formatter']['label'] = $form_state
      ->getValue('formatter_label');
    $this->configuration['formatter']['type'] = $form_state
      ->getValue('formatter_type');

    // @todo Remove this manual cast after https://www.drupal.org/node/2635236
    //   is resolved.
    $this->configuration['formatter']['settings'] = (array) $form_state
      ->getValue('formatter_settings');
  }

  /**
   * Gets the field definition.
   *
   * @return \Drupal\Core\Field\FieldDefinitionInterface
   *   The field definition.
   */
  protected function getFieldDefinition() {
    if (empty($this->fieldDefinition)) {
      $field_map = $this->entityFieldManager
        ->getFieldMap();
      $bundle = reset($field_map[$this->entityTypeId][$this->fieldName]['bundles']);
      $field_definitions = $this->entityFieldManager
        ->getFieldDefinitions($this->entityTypeId, $bundle);
      $this->fieldDefinition = $field_definitions[$this->fieldName];
    }
    return $this->fieldDefinition;
  }

  /**
   * Gets the field storage definition.
   *
   * @return \Drupal\Core\Field\FieldStorageDefinitionInterface
   *   The field storage definition.
   */
  protected function getFieldStorageDefinition() {
    if (empty($this->fieldStorageDefinition)) {
      $field_definitions = $this->entityFieldManager
        ->getFieldStorageDefinitions($this->entityTypeId);
      $this->fieldStorageDefinition = $field_definitions[$this->fieldName];
    }
    return $this->fieldStorageDefinition;
  }

  /**
   * Gets field type definition.
   *
   * @return array
   *   The field type definition.
   */
  protected function getFieldTypeDefinition() {
    return $this->fieldTypeManager
      ->getDefinition($this
      ->getFieldStorageDefinition()
      ->getType());
  }

  /**
   * Gets the formatter options for this field type.
   *
   * @return array
   *   The formatter options.
   */
  protected function getFormatterOptions() {
    return $this->formatterManager
      ->getOptions($this
      ->getFieldStorageDefinition()
      ->getType());
  }

  /**
   * Gets the formatter object.
   *
   * @param string $type
   *   The formatter name.
   * @param string $label
   *   The label option for the formatter.
   * @param array $settings
   *   The formatter settings.
   * @param array $third_party_settings
   *   The formatter third party settings.
   *
   * @return \Drupal\Core\Field\FormatterInterface
   *   The formatter object.
   */
  protected function getFormatter($type, $label, array $settings, array $third_party_settings) {
    return $this->formatterManager
      ->createInstance($type, [
      'field_definition' => $this
        ->getFieldDefinition(),
      'view_mode' => 'default',
      'prepare' => TRUE,
      'label' => $label,
      'settings' => $settings,
      'third_party_settings' => $third_party_settings,
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function __wakeup() {
    parent::__wakeup();

    // @todo figure out why this happens.
    // prevent $fieldStorageDefinition being erroneously set to $this.
    $this->fieldStorageDefinition = NULL;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BlockPluginInterface::BLOCK_LABEL_VISIBLE constant Indicates the block label (title) should be displayed to end users.
BlockPluginTrait::$transliteration protected property The transliteration service.
BlockPluginTrait::access public function
BlockPluginTrait::baseConfigurationDefaults protected function Returns generic default configuration for block plugins.
BlockPluginTrait::blockValidate public function 3
BlockPluginTrait::buildConfigurationForm public function Creates a generic configuration form for all block types. Individual block plugins can add elements to this form by overriding BlockBase::blockForm(). Most block plugins should not override this method unless they need to alter the generic form elements. 2
BlockPluginTrait::calculateDependencies public function
BlockPluginTrait::getConfiguration public function 1
BlockPluginTrait::getMachineNameSuggestion public function 1
BlockPluginTrait::getPreviewFallbackString public function 3
BlockPluginTrait::label public function
BlockPluginTrait::setConfiguration public function
BlockPluginTrait::setConfigurationValue public function
BlockPluginTrait::setTransliteration public function Sets the transliteration service.
BlockPluginTrait::submitConfigurationForm public function Most block plugins should not override this method. To add submission handling for a specific block type, override BlockBase::blockSubmit().
BlockPluginTrait::transliteration protected function Wraps the transliteration service.
BlockPluginTrait::validateConfigurationForm public function Most block plugins should not override this method. To add validation for a specific block type, override BlockBase::blockValidate(). 1
ContextAwarePluginAssignmentTrait::addContextAssignmentElement protected function Builds a form element for assigning a context to a given slot.
ContextAwarePluginAssignmentTrait::contextHandler protected function Wraps the context handler.
ContextAwarePluginBase::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginBase::$contexts Deprecated private property Data objects representing the contexts passed in the plugin configuration.
ContextAwarePluginBase::createContextFromConfiguration protected function Overrides ContextAwarePluginBase::createContextFromConfiguration
ContextAwarePluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts 9
ContextAwarePluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge 7
ContextAwarePluginBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags 4
ContextAwarePluginBase::getContext public function This code is identical to the Component in order to pick up a different Context class. Overrides ContextAwarePluginBase::getContext
ContextAwarePluginBase::getContextDefinition public function Overrides ContextAwarePluginBase::getContextDefinition
ContextAwarePluginBase::getContextDefinitions public function Overrides ContextAwarePluginBase::getContextDefinitions
ContextAwarePluginBase::getContextMapping public function Gets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::getContextMapping
ContextAwarePluginBase::getContexts public function Gets the defined contexts. Overrides ContextAwarePluginInterface::getContexts
ContextAwarePluginBase::getContextValue public function Gets the value for a defined context. Overrides ContextAwarePluginInterface::getContextValue
ContextAwarePluginBase::getContextValues public function Gets the values for all defined contexts. Overrides ContextAwarePluginInterface::getContextValues
ContextAwarePluginBase::setContext public function Set a context on this plugin. Overrides ContextAwarePluginBase::setContext
ContextAwarePluginBase::setContextMapping public function Sets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::setContextMapping
ContextAwarePluginBase::setContextValue public function Sets the value for a defined context. Overrides ContextAwarePluginBase::setContextValue
ContextAwarePluginBase::validateContexts public function Validates the set values for the defined contexts. Overrides ContextAwarePluginInterface::validateContexts
ContextAwarePluginBase::__get public function Implements magic __get() method.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
EntityField::$entityFieldManager protected property The entity field manager.
EntityField::$entityTypeId protected property The entity type id.
EntityField::$entityTypeManager protected property The entity type manager.
EntityField::$fieldDefinition protected property The field definition.
EntityField::$fieldName protected property The field name.
EntityField::$fieldStorageDefinition protected property The field storage definition.
EntityField::$fieldTypeManager protected property The field type manager.
EntityField::$formatterManager protected property The formatter manager.
EntityField::blockAccess protected function Indicates whether the block should be shown. Overrides BlockPluginTrait::blockAccess
EntityField::blockForm public function Overrides BlockPluginTrait::blockForm
EntityField::blockSubmit public function Overrides BlockPluginTrait::blockSubmit
EntityField::build public function Builds and returns the renderable array for this block plugin. Overrides BlockPluginInterface::build
EntityField::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
EntityField::defaultConfiguration public function Overrides BlockPluginTrait::defaultConfiguration
EntityField::formatterSettingsAjaxCallback public static function Render API callback: gets the layout settings elements.
EntityField::formatterSettingsProcessCallback public function Render API callback: builds the formatter settings elements.
EntityField::getFieldDefinition protected function Gets the field definition.
EntityField::getFieldStorageDefinition protected function Gets the field storage definition.
EntityField::getFieldTypeDefinition protected function Gets field type definition.
EntityField::getFormatter protected function Gets the formatter object.
EntityField::getFormatterOptions protected function Gets the formatter options for this field type.
EntityField::__construct public function Constructs a new EntityField. Overrides BlockPluginTrait::__construct
EntityField::__wakeup public function Overrides DependencySerializationTrait::__wakeup
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginWithFormsTrait::getFormClass public function
PluginWithFormsTrait::hasFormClass public function
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2