EntityDisplayBase.php 9.29 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

/**
 * @file
 * Contains \Drupal\entity\EntityDisplayBase.
 */

namespace Drupal\entity;

use Drupal\Core\Config\Entity\ConfigEntityBase;
11
use Drupal\Core\Entity\Display\EntityDisplayInterface;
12
use Drupal\Core\Entity\ContentEntityInterface;
13 14 15 16 17

/**
 * Base class for config entity types that store configuration for entity forms
 * and displays.
 */
18
abstract class EntityDisplayBase extends ConfigEntityBase implements EntityDisplayInterface {
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

  /**
   * Unique ID for the config entity.
   *
   * @var string
   */
  public $id;

  /**
   * Unique UUID for the config entity.
   *
   * @var string
   */
  public $uuid;

  /**
   * Entity type to be displayed.
   *
   * @var string
   */
  public $targetEntityType;

  /**
   * Bundle to be displayed.
   *
   * @var string
   */
  public $bundle;

48 49 50 51 52 53 54 55 56 57 58
  /**
   * A partial entity, created via _field_create_entity_from_ids() from
   * $targetEntityType and $bundle.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   *
   * @todo Remove when getFieldDefinition() is fixed to not need it.
   *   https://drupal.org/node/2114707
   */
  private $targetEntity;

59 60 61 62 63 64 65
  /**
   * View or form mode to be displayed.
   *
   * @var string
   */
  public $mode;

66 67 68 69 70 71 72 73
  /**
   * Whether this display is enabled or not. If the entity (form) display
   * is disabled, we'll fall back to the 'default' display.
   *
   * @var boolean
   */
  public $status;

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  /**
   * List of component display options, keyed by component name.
   *
   * @var array
   */
  protected $content = array();

  /**
   * The original view or form mode that was requested (case of view/form modes
   * being configured to fall back to the 'default' display).
   *
   * @var string
   */
  public $originalMode;

  /**
   * The plugin objects used for this display, keyed by field name.
   *
   * @var array
   */
  protected $plugins = array();

  /**
   * Context in which this entity will be used (e.g. 'display', 'form').
   *
   * @var string
   */
  protected $displayContext;

  /**
   * The plugin manager used by this entity type.
   *
   * @var \Drupal\Component\Plugin\PluginManagerBase
   */
  protected $pluginManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $values, $entity_type) {
    // @todo See http://drupal.org/node/1825044#comment-6847792: contact.module
    // currently produces invalid entities with a NULL bundle in some cases.
    // Add the validity checks back when http://drupal.org/node/1856556 is
    // fixed.
    // if (!isset($values['targetEntityType']) || !isset($values['bundle']) || !isset($values['mode'])) {
    //   throw new \InvalidArgumentException('Missing required properties for an EntityDisplay entity.');
    // }

    // A plugin manager and a context type needs to be set by extending classes.
    if (!isset($this->pluginManager)) {
      throw new \RuntimeException('Missing plugin manager.');
    }
    if (!isset($this->displayContext)) {
      throw new \RuntimeException('Missing display context type.');
    }

    parent::__construct($values, $entity_type);

    $this->originalMode = $this->mode;
  }

  /**
   * {@inheritdoc}
   */
  public function id() {
    return $this->targetEntityType . '.' . $this->bundle . '.' . $this->mode;
  }

  /**
   * {@inheritdoc}
144 145 146 147 148
   */
  public function save() {
    $return = parent::save();

    // Reset the render cache for the target entity type.
149 150
    if (\Drupal::entityManager()->hasController($this->targetEntityType, 'view_builder')) {
      \Drupal::entityManager()->getViewBuilder($this->targetEntityType)->resetCache();
151 152 153 154 155 156 157
    }

    return $return;
  }

  /**
   * {@inheritdoc}
158 159 160 161 162 163 164 165 166
   */
  public function getExportProperties() {
    $names = array(
      'id',
      'uuid',
      'targetEntityType',
      'bundle',
      'mode',
      'content',
167
      'status',
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    );
    $properties = array();
    foreach ($names as $name) {
      $properties[$name] = $this->get($name);
    }
    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function createCopy($mode) {
    $display = $this->createDuplicate();
    $display->mode = $display->originalMode = $mode;
    return $display;
  }

  /**
   * {@inheritdoc}
   */
  public function getComponents() {
    $result = array();
    foreach ($this->content as $name => $options) {
191
      if (!isset($options['visible']) || $options['visible'] == TRUE) {
192 193 194 195 196 197 198 199 200 201 202
        unset($options['visible']);
        $result[$name] = $options;
      }
    }
    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function getComponent($name) {
203 204 205 206 207 208 209 210 211 212 213 214 215 216
    // Until https://drupal.org/node/2144919 allows base fields to be configured
    // in the UI, many base fields are also still registered as "extra fields"
    // to keep appearing in the "Manage (form) display" screens.
    // - Field UI still treats them as "base fields", saving only the weight
    //   and visibility flag in the EntityDisplay.
    // - For some of them (e.g. node title), the custom rendering code has been
    //   removed in favor of regular widgets/formatters. Their display options
    //   are "upgraded" to those of a field (widget/formatter + settings) at
    //   runtime using hook_entity_display_alter().
    // The getComponent() / setComponent() methods handle this by treating
    // components as "extra fields" if they are registered as such, *and* if
    // their display options contain no 'type' entry specifying a widget or
    // formatter.
    // @todo Cleanup after https://drupal.org/node/2144919 is fixed.
217
    $extra_fields = field_info_extra_fields($this->targetEntityType, $this->bundle, $this->displayContext);
218
    if (isset($extra_fields[$name]) && !isset($this->content[$name]['type'])) {
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
      // If we have explicit settings, return an array or NULL depending on
      // visibility.
      if (isset($this->content[$name])) {
        if ($this->content[$name]['visible']) {
          return array(
            'weight' => $this->content[$name]['weight'],
          );
        }
        else {
          return NULL;
        }
      }

      // If no explicit settings for the extra field, look at the default
      // visibility in its definition.
      $definition = $extra_fields[$name];
      if (!isset($definition['visible']) || $definition['visible'] == TRUE) {
        return array(
          'weight' => $definition['weight']
        );
      }
      else {
        return NULL;
      }
    }
244
    elseif (isset($this->content[$name])) {
245 246 247 248 249 250 251 252 253 254 255 256 257
      return $this->content[$name];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function setComponent($name, array $options = array()) {
    // If no weight specified, make sure the field sinks at the bottom.
    if (!isset($options['weight'])) {
      $max = $this->getHighestWeight();
      $options['weight'] = isset($max) ? $max + 1 : 0;
    }
258 259
    // See remark in getComponent().
    // @todo Cleanup after https://drupal.org/node/2144919 is fixed.
260
    $extra_fields = field_info_extra_fields($this->targetEntityType, $this->bundle, $this->displayContext);
261
    if (isset($extra_fields[$name]) && !isset($options['type'])) {
262 263
      $options['visible'] = TRUE;
    }
264
    elseif ($field_definition = $this->getFieldDefinition($name)) {
265
      $options = $this->pluginManager->prepareConfiguration($field_definition->getType(), $options);
266 267 268 269
    }

    // Clear the persisted plugin, if any.
    unset($this->plugins[$name]);
270 271 272 273 274 275 276 277 278 279

    $this->content[$name] = $options;

    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function removeComponent($name) {
280 281
    // See remark in getComponent().
    // @todo Cleanup after https://drupal.org/node/2144919 is fixed.
282
    $extra_fields = field_info_extra_fields($this->targetEntityType, $this->bundle, $this->displayContext);
283
    if (isset($extra_fields[$name]) && !isset($this->content[$name]['type'])) {
284 285 286 287 288 289 290 291 292 293 294 295
      // 'Extra fields' are exposed in hooks and can appear at any given time.
      // Therefore we store extra fields that are explicitly being hidden, so
      // that we can differenciate with those that are simply not configured
      // yet.
      $this->content[$name] = array(
        'visible' => FALSE,
      );
    }
    else {
      unset($this->content[$name]);
    }

296 297
    unset($this->plugins[$name]);

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getHighestWeight() {
    $weights = array();

    // Collect weights for the components in the display.
    foreach ($this->content as $options) {
      if (isset($options['weight'])) {
        $weights[] = $options['weight'];
      }
    }

    // Let other modules feedback about their own additions.
    $weights = array_merge($weights, module_invoke_all('field_info_max_weight', $this->targetEntityType, $this->bundle, $this->displayContext, $this->mode));

    return $weights ? max($weights) : NULL;
  }

320 321 322 323 324 325 326 327 328 329 330 331 332 333
  /**
   * Returns the field definition of a field.
   */
  protected function getFieldDefinition($field_name) {
    // @todo Replace this entire implementation with
    //   \Drupal::entityManager()->getFieldDefinition() when it can hand the
    //   $instance objects - https://drupal.org/node/2114707
    if (!isset($this->targetEntity)) {
      $this->targetEntity = _field_create_entity_from_ids((object) array('entity_type' => $this->targetEntityType, 'bundle' => $this->bundle, 'entity_id' => NULL));
    }
    if (($this->targetEntity instanceof ContentEntityInterface) && $this->targetEntity->hasField($field_name)) {
      return $this->targetEntity->get($field_name)->getFieldDefinition();
    }
  }
334
}