entity.inc 14.4 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Entity API for handling entities like nodes or users.
 */

8
use Drupal\Core\Cache\Cache;
9 10
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityInterface;
11

12 13 14 15 16 17
/**
 * Clears the entity render cache for all entity types.
 */
function entity_render_cache_clear() {
  $entity_manager = Drupal::entityManager();
  foreach ($entity_manager->getDefinitions() as $entity_type => $info) {
18
    if ($entity_manager->hasHandler($entity_type, 'view_builder')) {
19
      $entity_manager->getViewBuilder($entity_type)->resetCache();
20 21 22 23
    }
  }
}

24
/**
25
 * Returns the entity bundle info.
26
 *
27 28 29 30 31 32
 * @param string|null $entity_type
 *   The entity type whose bundle info should be returned, or NULL for all
 *   bundles info. Defaults to NULL.
 *
 * @return array
 *   The bundle info for a specific entity type, or all entity types.
33
 *
34 35
 * @see \Drupal\Core\Entity\EntityManagerInterface::getBundleInfo()
 * @see \Drupal\Core\Entity\EntityManagerInterface::getAllBundleInfo()
36 37
 */
function entity_get_bundles($entity_type = NULL) {
38
  if (isset($entity_type)) {
39
    return \Drupal::entityManager()->getBundleInfo($entity_type);
40
  }
41
  else {
42
    return \Drupal::entityManager()->getAllBundleInfo();
43 44 45
  }
}

46
/**
47 48 49 50
 * Loads an entity from the database.
 *
 * @param string $entity_type
 *   The entity type to load, e.g. node or user.
51
 * @param mixed $id
52 53 54 55
 *   The id of the entity to load.
 * @param bool $reset
 *   Whether to reset the internal cache for the requested entity type.
 *
56 57
 * @return \Drupal\Core\Entity\EntityInterface|null
 *   The entity object, or NULL if there is no entity with the given ID.
58
 *
59
 * @see \Drupal\Core\Entity\EntityManagerInterface
60
 * @see \Drupal\Core\Entity\EntityStorageInterface
61
 * @see \Drupal\Core\Entity\Sql\SqlContentEntityStorage
62
 * @see \Drupal\Core\Entity\Query\QueryInterface
63 64
 */
function entity_load($entity_type, $id, $reset = FALSE) {
65
  $controller = \Drupal::entityManager()->getStorage($entity_type);
66 67 68 69
  if ($reset) {
    $controller->resetCache(array($id));
  }
  return $controller->load($id);
70 71
}

72 73 74 75 76 77 78 79
/**
 * Loads an entity from the database.
 *
 * @param string $entity_type
 *   The entity type to load, e.g. node or user.
 * @param int $revision_id
 *   The id of the entity to load.
 *
80 81
 * @return \Drupal\Core\Entity\EntityInterface|null
 *   The entity object, or NULL if there is no entity with the given revision
82 83
 *   id.
 *
84
 * @see \Drupal\Core\Entity\EntityManagerInterface
85
 * @see \Drupal\Core\Entity\EntityStorageInterface
86
 * @see \Drupal\Core\Entity\Sql\SqlContentEntityStorage
87 88
 */
function entity_revision_load($entity_type, $revision_id) {
89
  return \Drupal::entityManager()
90
    ->getStorage($entity_type)
91
    ->loadRevision($revision_id);
92 93
}

94
/**
95
 * Deletes an entity revision.
96 97 98 99 100 101 102
 *
 * @param string $entity_type
 *   The entity type to load, e.g. node or user.
 * @param $revision_id
 *   The revision ID to delete.
 */
function entity_revision_delete($entity_type, $revision_id) {
103
  \Drupal::entityManager()
104
    ->getStorage($entity_type)
105
    ->deleteRevision($revision_id);
106 107
}

108 109 110 111 112
/**
 * Loads an entity by UUID.
 *
 * Note that some entity types may not support UUIDs.
 *
113
 * @param string $entity_type_id
114 115 116 117 118 119 120
 *   The entity type to load; e.g., 'node' or 'user'.
 * @param string $uuid
 *   The UUID of the entity to load.
 *
 * @return EntityInterface|FALSE
 *   The entity object, or FALSE if there is no entity with the given UUID.
 *
121
 * @throws \Drupal\Core\Entity\EntityStorageException
122 123
 *   Thrown in case the requested entity type does not support UUIDs.
 *
124
 * @see \Drupal\Core\Entity\EntityManagerInterface
125 126
 *
 * @deprecated Use \Drupal::entityManager()->loadEntityByUuid();
127
 */
128 129
function entity_load_by_uuid($entity_type_id, $uuid) {
  return \Drupal::entityManager()->loadEntityByUuid($entity_type_id, $uuid);
130 131
}

132 133
/**
 * Loads multiple entities from the database.
134 135 136 137 138 139
 *
 * This function should be used whenever you need to load more than one entity
 * from the database. The entities are loaded into memory and will not require
 * database access if loaded again during the same page request.
 *
 * The actual loading is done through a class that has to implement the
140
 * Drupal\Core\Entity\EntityStorageInterface interface. By default,
141
 * Drupal\Core\Entity\Sql\SqlContentEntityStorage is used for content entities
142 143
 * and Drupal\Core\Config\Entity\ConfigEntityStorage for config entities. Entity
 * types can specify that a different class should be used by setting the
144
 * "controllers['storage']" key in the entity plugin annotation. These classes
145
 * can either implement the Drupal\Core\Entity\EntityStorageInterface
146
 * interface, or, most commonly, extend the
147
 * Drupal\Core\Entity\Sql\SqlContentEntityStorage class.
148
 * See Drupal\node\Entity\Node and Drupal\node\NodeStorage
149
 * for an example.
150
 *
151
 * @param string $entity_type
152
 *   The entity type to load, e.g. node or user.
153 154
 * @param array $ids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
155
 * @param bool $reset
156 157
 *   Whether to reset the internal cache for the requested entity type.
 *
158
 * @return array
159
 *   An array of entity objects indexed by their IDs.
160
 *
161
 * @see \Drupal\Core\Entity\EntityManagerInterface
162
 * @see \Drupal\Core\Entity\EntityStorageInterface
163
 * @see \Drupal\Core\Entity\Sql\SqlContentEntityStorage
164
 * @see \Drupal\Core\Entity\Query\QueryInterface
165
 */
166
function entity_load_multiple($entity_type, array $ids = NULL, $reset = FALSE) {
167
  $controller = \Drupal::entityManager()->getStorage($entity_type);
168
  if ($reset) {
169
    $controller->resetCache($ids);
170
  }
171
  return $controller->loadMultiple($ids);
172 173 174 175 176 177 178 179 180 181 182 183
}

/**
 * Load entities by their property values.
 *
 * @param string $entity_type
 *   The entity type to load, e.g. node or user.
 * @param array $values
 *   An associative array where the keys are the property names and the
 *   values are the values those properties must have.
 *
 * @return array
184 185
 *   An array of entity objects indexed by their IDs. Returns an empty array if
 *   no matching entities found.
186 187
 */
function entity_load_multiple_by_properties($entity_type, array $values) {
188
  return \Drupal::entityManager()
189
    ->getStorage($entity_type)
190
    ->loadByProperties($values);
191 192 193 194 195 196 197 198 199 200 201 202 203
}

/**
 * Loads the unchanged, i.e. not modified, entity from the database.
 *
 * Unlike entity_load() this function ensures the entity is directly loaded from
 * the database, thus bypassing any static cache. In particular, this function
 * is useful to determine changes by comparing the entity being saved to the
 * stored entity.
 *
 * @param $entity_type
 *   The entity type to load, e.g. node or user.
 * @param $id
204
 *   The ID of the entity to load.
205 206 207 208 209
 *
 * @return
 *   The unchanged entity, or FALSE if the entity cannot be loaded.
 */
function entity_load_unchanged($entity_type, $id) {
210
  return \Drupal::entityManager()
211
    ->getStorage($entity_type)
212
    ->loadUnchanged($id);
213 214
}

215 216 217
/**
 * Deletes multiple entities permanently.
 *
218
 * @param string $entity_type
219
 *   The type of the entity.
220
 * @param array $ids
221 222
 *   An array of entity IDs of the entities to delete.
 */
223
function entity_delete_multiple($entity_type, array $ids) {
224
  $controller = \Drupal::entityManager()->getStorage($entity_type);
225
  $entities = $controller->loadMultiple($ids);
226
  $controller->delete($entities);
227 228 229
}

/**
230
 * Constructs a new entity object, without permanently saving it.
231
 *
232
 * @param string $entity_type
233
 *   The type of the entity.
234 235 236
 * @param array $values
 *   (optional) An array of values to set, keyed by property name. If the
 *   entity type has bundles, the bundle key has to be specified.
237
 *
238
 * @return \Drupal\Core\Entity\EntityInterface
239 240
 *   A new entity object.
 */
241
function entity_create($entity_type, array $values = array()) {
242
  return \Drupal::entityManager()
243
    ->getStorage($entity_type)
244
    ->create($values);
245 246
}

247 248 249
/**
 * Returns the label of an entity.
 *
250
 * This is a wrapper for Drupal\Core\Entity\EntityInterface::label(). This function
251
 * should only be used as a callback, e.g. for menu title callbacks.
252
 *
253
 * @param \Drupal\Core\Entity\EntityInterface $entity
254
 *   The entity for which to generate the label.
255 256 257 258
 * @param $langcode
 *   (optional) The language code of the language that should be used for
 *   getting the label. If set to NULL, the entity's default language is
 *   used.
259 260
 *
 * @return
261
 *   The label of the entity, or NULL if there is no label defined.
262
 *
263
 * @see \Drupal\Core\Entity\EntityInterface::label()
264
 */
265 266
function entity_page_label(EntityInterface $entity, $langcode = NULL) {
  return $entity->label($langcode);
267 268
}

269 270 271
/**
 * Returns the render array for an entity.
 *
272
 * @param \Drupal\Core\Entity\EntityInterface $entity
273 274 275 276 277 278
 *   The entity to be rendered.
 * @param string $view_mode
 *   The view mode that should be used to display the entity.
 * @param string $langcode
 *   (optional) For which language the entity should be rendered, defaults to
 *   the current content language.
279 280 281
 * @param bool $reset
 *   (optional) Whether to reset the render cache for the requested entity.
 *   Defaults to FALSE.
282 283 284 285
 *
 * @return array
 *   A render array for the entity.
 */
286
function entity_view(EntityInterface $entity, $view_mode, $langcode = NULL, $reset = FALSE) {
287
  $render_controller = \Drupal::entityManager()->getViewBuilder($entity->getEntityTypeId());
288 289 290 291
  if ($reset) {
    $render_controller->resetCache(array($entity->id()));
  }
  return $render_controller->view($entity, $view_mode, $langcode);
292 293 294 295 296
}

/**
 * Returns the render array for the provided entities.
 *
297
 * @param \Drupal\Core\Entity\EntityInterface[] $entities
298 299 300 301 302 303
 *   The entities to be rendered, must be of the same type.
 * @param string $view_mode
 *   The view mode that should be used to display the entity.
 * @param string $langcode
 *   (optional) For which language the entity should be rendered, defaults to
 *   the current content language.
304 305 306
 * @param bool $reset
 *   (optional) Whether to reset the render cache for the requested entities.
 *   Defaults to FALSE.
307 308 309 310 311
 *
 * @return array
 *   A render array for the entities, indexed by the same keys as the
 *   entities array passed in $entities.
 */
312
function entity_view_multiple(array $entities, $view_mode, $langcode = NULL, $reset = FALSE) {
313
  $render_controller = \Drupal::entityManager()->getViewBuilder(reset($entities)->getEntityTypeId());
314 315 316 317
  if ($reset) {
    $render_controller->resetCache(array_keys($entities));
  }
  return $render_controller->viewMultiple($entities, $view_mode, $langcode);
318
}
319

320
/**
321
 * Returns the entity view display associated to a bundle and view mode.
322 323 324 325 326 327
 *
 * Use this function when assigning suggested display options for a component
 * in a given view mode. Note that they will only be actually used at render
 * time if the view mode itself is configured to use dedicated display settings
 * for the bundle; if not, the 'default' display is used instead.
 *
328 329 330 331 332
 * The function reads the entity view display from the current configuration, or
 * returns a ready-to-use empty one if configuration entry exists yet for this
 * bundle and view mode. This streamlines manipulation of display objects by
 * always returning a consistent object that reflects the current state of the
 * configuration.
333 334 335 336 337
 *
 * Example usage:
 * - Set the 'body' field to be displayed and the 'field_image' field to be
 *   hidden on article nodes in the 'default' display.
 * @code
338
 * entity_get_display('node', 'article', 'default')
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
 *   ->setComponent('body', array(
 *     'type' => 'text_summary_or_trimmed',
 *     'settings' => array('trim_length' => '200')
 *     'weight' => 1,
 *   ))
 *   ->removeComponent('field_image')
 *   ->save();
 * @endcode
 *
 * @param string $entity_type
 *   The entity type.
 * @param string $bundle
 *   The bundle.
 * @param string $view_mode
 *   The view mode, or 'default' to retrieve the 'default' display object for
 *   this bundle.
 *
356
 * @return \Drupal\Core\Entity\Display\EntityViewDisplayInterface
357
 *   The entity view display associated to the view mode.
358 359 360
 */
function entity_get_display($entity_type, $bundle, $view_mode) {
  // Try loading the display from configuration.
361
  $display = entity_load('entity_view_display', $entity_type . '.' . $bundle . '.' . $view_mode);
362 363

  // If not found, create a fresh display object. We do not preemptively create
364 365 366 367
  // new entity_view_display configuration entries for each existing entity type
  // and bundle whenever a new view mode becomes available. Instead,
  // configuration entries are only created when a display object is explicitly
  // configured and saved.
368
  if (!$display) {
369
    $display = entity_create('entity_view_display', array(
370 371
      'targetEntityType' => $entity_type,
      'bundle' => $bundle,
372
      'mode' => $view_mode,
373
      'status' => TRUE,
374 375 376 377 378 379
    ));
  }

  return $display;
}

380
/**
381
 * Returns the entity form display associated to a bundle and form mode.
382
 *
383 384
 * The function reads the entity form display object from the current
 * configuration, or returns a ready-to-use empty one if no configuration entry
385
 * exists yet for this bundle and form mode. This streamlines manipulation of
386 387
 * entity form displays by always returning a consistent object that reflects
 * the current state of the configuration.
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
 *
 * Example usage:
 * - Set the 'body' field to be displayed with the 'text_textarea_with_summary'
 *   widget and the 'field_image' field to be hidden on article nodes in the
 *  'default' form mode.
 * @code
 * entity_get_form_display('node', 'article', 'default')
 *   ->setComponent('body', array(
 *     'type' => 'text_textarea_with_summary',
 *     'weight' => 1,
 *   ))
 *   ->setComponent('field_image', array(
 *     'type' => 'hidden',
 *   ))
 *   ->save();
 * @endcode
 *
 * @param string $entity_type
 *   The entity type.
 * @param string $bundle
 *   The bundle.
 * @param string $form_mode
 *   The form mode.
 *
412
 * @return \Drupal\Core\Entity\Display\EntityFormDisplayInterface
413
 *   The entity form display associated to the given form mode.
414 415 416 417 418 419
 */
function entity_get_form_display($entity_type, $bundle, $form_mode) {
  // Try loading the entity from configuration.
  $entity_form_display = entity_load('entity_form_display', $entity_type . '.' . $bundle . '.' . $form_mode);

  // If not found, create a fresh entity object. We do not preemptively create
420
  // new entity form display configuration entries for each existing entity type
421
  // and bundle whenever a new form mode becomes available. Instead,
422
  // configuration entries are only created when an entity form display is
423 424 425 426 427 428
  // explicitly configured and saved.
  if (!$entity_form_display) {
    $entity_form_display = entity_create('entity_form_display', array(
      'targetEntityType' => $entity_type,
      'bundle' => $bundle,
      'mode' => $form_mode,
429
      'status' => TRUE,
430 431 432 433 434
    ));
  }

  return $entity_form_display;
}