You are here

entity_reference_display.module in Entity Reference Display 8

Entity Reference Display module.

File

entity_reference_display.module
View source
<?php

/**
 * @file
 * Entity Reference Display module.
 */
use Drupal\Component\Utility\Html;
use Drupal\Core\Form\FormStateInterface;
use Drupal\entity_reference_display\Plugin\Field\FieldFormatter\EntityReferenceRevisionsDisplayFormatter;

/**
 * Implements hook_form_alter().
 */
function entity_reference_display_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  switch ($form_id) {

    // Disable cardinality settings for 1 value limit.
    case 'field_storage_config_edit_form':

      /** @var \Drupal\field\Entity\FieldConfig $field_config */
      $field_config = $form_state
        ->getStorage()['field_config'];

      // Only for display mode field.
      if ($field_config
        ->getType() == 'entity_reference_display') {

        // Disable editing by user.
        $form['cardinality_container']['#disabled'] = TRUE;

        // Remove states settings to disable JS widget.
        unset($form['cardinality_container']['cardinality_number']['#states']);
      }
      break;
  }
}

/**
 * Implements hook_field_widget_info_alter().
 */
function entity_reference_display_field_widget_info_alter(array &$info) {

  // Allow to use the same widgets as list_string field type.
  entity_reference_display_set_available_plugins($info);
}

/**
 * Implements hook_field_formatter_info_alter().
 */
function entity_reference_display_field_formatter_info_alter(array &$info) {

  // Allow to use the same formatters as list_string field type.
  entity_reference_display_set_available_plugins($info);

  // Replace default formatter when revisions are supported.
  if (\Drupal::moduleHandler()
    ->moduleExists('entity_reference_revisions')) {
    $info['entity_reference_display_default']['class'] = EntityReferenceRevisionsDisplayFormatter::class;
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function entity_reference_display_preprocess_field(&$variables) {

  // Only for selected display mode formatter.
  if (isset($variables['element']['#formatter']) && $variables['element']['#formatter'] === 'entity_reference_display_default') {

    // Add display mode class for field wrapper.
    if (!empty($variables['element'][0]['#view_mode'])) {
      $class = 'erd-list--' . $variables['element'][0]['#view_mode'];
      $variables['attributes']['class'][] = Html::getClass($class);
    }
  }
}

/**
 * Set available widgets or formatters for display mode field.
 */
function entity_reference_display_set_available_plugins(array &$info) {

  // Search between all plugins for similar type.
  foreach ($info as &$plugin) {
    if (in_array('list_string', $plugin['field_types'])) {
      $plugin['field_types'][] = 'entity_reference_display';
    }
  }
}