entity.api.php 22.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php

/**
 * @file
 * Hooks provided the Entity module.
 */

/**
 * @addtogroup hooks
 * @{
 */

/**
14 15 16 17 18 19 20 21 22 23 24 25 26
 * Add to entity type definitions.
 *
 * Modules may implement this hook to add information to defined entity types.
 *
 * @param array $entity_info
 *   An associative array of all entity type definitions, keyed by the entity
 *   type name. Passed by reference.
 *
 * @see \Drupal\Core\Entity\Entity
 * @see \Drupal\Core\Entity\EntityManager
 * @see entity_get_info()
 */
function hook_entity_info(&$entity_info) {
27 28
  // Add a form controller for a custom node form without overriding the default
  // node form. To override the default node form, use hook_entity_info_alter()
29 30
  // to alter $entity_info['node']['controllers']['form']['default'].
  $entity_info['node']['controllers']['form']['mymodule_foo'] = 'Drupal\mymodule\NodeFooFormController';
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
}

/**
 * Describe the view modes for entity types.
 *
 * View modes let entities be displayed differently depending on the context.
 * For instance, a node can be displayed differently on its own page ('full'
 * mode), on the home page or taxonomy listings ('teaser' mode), or in an RSS
 * feed ('rss' mode). Modules taking part in the display of the entity (notably
 * the Field API) can adjust their behavior depending on the requested view
 * mode. An additional 'default' view mode is available for all entity types.
 * This view mode is not intended for actual entity display, but holds default
 * display settings. For each available view mode, administrators can configure
 * whether it should use its own set of field display settings, or just
 * replicate the settings of the 'default' view mode, thus reducing the amount
 * of display configurations to keep track of.
 *
 * @return array
 *   An associative array of all entity view modes, keyed by the entity
 *   type name, and then the view mode name, with the following keys:
 *   - label: The human-readable name of the view mode.
 *   - custom_settings: A boolean specifying whether the view mode should by
 *     default use its own custom field display settings. If FALSE, entities
 *     displayed in this view mode will reuse the 'default' display settings
 *     by default (e.g. right after the module exposing the view mode is
 *     enabled), but administrators can later use the Field UI to apply custom
 *     display settings specific to the view mode.
 *
 * @see entity_get_view_modes()
 * @see hook_entity_view_mode_info_alter()
 */
function hook_entity_view_mode_info() {
  $view_modes['user']['full'] = array(
    'label' => t('User account'),
65
  );
66 67 68 69 70 71 72 73 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
  $view_modes['user']['compact'] = array(
    'label' => t('Compact'),
    'custom_settings' => TRUE,
  );
  return $view_modes;
}

/**
 * Alter the view modes for entity types.
 *
 * @param array $view_modes
 *   An array of view modes, keyed first by entity type, then by view mode name.
 *
 * @see entity_get_view_modes()
 * @see hook_entity_view_mode_info()
 */
function hook_entity_view_mode_info_alter(&$view_modes) {
  $view_modes['user']['full']['custom_settings'] = TRUE;
}

/**
 * Describe the bundles for entity types.
 *
 * @return array
 *   An associative array of all entity bundles, keyed by the entity
 *   type name, and then the bundle name, with the following keys:
 *   - label: The human-readable name of the bundle.
 *   - uri_callback: The same as the 'uri_callback' key defined for the entity
 *     type in the EntityManager, but for the bundle only. When determining
 *     the URI of an entity, if a 'uri_callback' is defined for both the
 *     entity type and the bundle, the one for the bundle is used.
 *   - admin: An array of information that allows Field UI pages to attach
 *     themselves to the existing administration pages for the bundle.
 *     Elements:
 *     - path: the path of the bundle's main administration page, as defined
 *       in hook_menu(). If the path includes a placeholder for the bundle,
 *       the 'bundle argument', 'bundle helper' and 'real path' keys below
 *       are required.
 *     - bundle argument: The position of the placeholder in 'path', if any.
 *     - real path: The actual path (no placeholder) of the bundle's main
 *       administration page. This will be used to generate links.
 *     - access callback: As in hook_menu(). 'user_access' will be assumed if
 *       no value is provided.
 *     - access arguments: As in hook_menu().
110 111
 *   - translatable: (optional) A boolean value specifying whether this bundle
 *     has translation support enabled. Defaults to FALSE.
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
 *
 * @see entity_get_bundles()
 * @see hook_entity_bundle_info_alter()
 */
function hook_entity_bundle_info() {
  $bundles['user']['user'] = array(
    'label' => t('User'),
    'admin' => array(
      'path' => 'admin/config/people/accounts',
    ),
  );
  return $bundles;
}

/**
 * Alter the bundles for entity types.
 *
 * @param array $bundles
 *   An array of bundles, keyed first by entity type, then by bundle name.
 *
 * @see entity_get_bundles()
 * @see hook_entity_bundle_info()
 */
function hook_entity_bundle_info_alter(&$bundles) {
  $bundles['user']['user']['label'] = t('Full account');
137 138
}

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
/**
 * Act on entity_bundle_create().
 *
 * This hook is invoked after the operation has been performed.
 *
 * @param string $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param string $bundle
 *   The name of the bundle.
 */
function hook_entity_bundle_create($entity_type, $bundle) {
  // When a new bundle is created, the menu needs to be rebuilt to add the
  // Field UI menu item tabs.
  state()->set('menu_rebuild_needed', TRUE);
}

/**
 * Act on entity_bundle_rename().
 *
 * This hook is invoked after the operation has been performed.
 *
 * @param string $entity_type
 *   The entity type to which the bundle is bound.
 * @param string $bundle_old
 *   The previous name of the bundle.
 * @param string $bundle_new
 *   The new name of the bundle.
 */
function hook_entity_bundle_rename($entity_type, $bundle_old, $bundle_new) {
  // Update the settings associated with the bundle in my_module.settings.
  $config = config('my_module.settings');
  $bundle_settings = $config->get('bundle_settings');
  if (isset($bundle_settings[$entity_type][$bundle_old])) {
    $bundle_settings[$entity_type][$bundle_new] = $bundle_settings[$entity_type][$bundle_old];
    unset($bundle_settings[$entity_type][$bundle_old]);
    $config->set('bundle_settings', $bundle_settings);
  }
}

/**
 * Act on entity_bundle_delete().
 *
 * This hook is invoked after the operation has been performed.
 *
 * @param string $entity_type
 *   The type of entity; for example, 'node' or 'user'.
 * @param string $bundle
 *   The bundle that was just deleted.
 */
function hook_entity_bundle_delete($entity_type, $bundle) {
  // Remove the settings associated with the bundle in my_module.settings.
  $config = config('my_module.settings');
  $bundle_settings = $config->get('bundle_settings');
  if (isset($bundle_settings[$entity_type][$bundle])) {
    unset($bundle_settings[$entity_type][$bundle]);
    $config->set('bundle_settings', $bundle_settings);
  }
}

198 199
/**
 * Alter the entity type definitions.
200 201
 *
 * Modules may implement this hook to alter the information that defines an
202
 * entity type. All properties that are available in
203 204
 * \Drupal\Core\Entity\EntityManager can be altered here.
 *
205 206 207
 * Do not use this hook to add information to entity types. Use
 * hook_entity_info() for that instead.
 *
208 209
 * @param array $entity_info
 *   An associative array of all entity type definitions, keyed by the entity
210
 *   type name. Passed by reference.
211
 *
212 213 214
 * @see \Drupal\Core\Entity\Entity
 * @see \Drupal\Core\Entity\EntityManager
 * @see entity_get_info()
215 216 217
 */
function hook_entity_info_alter(&$entity_info) {
  // Set the controller class for nodes to an alternate implementation of the
218
  // Drupal\Core\Entity\EntityStorageControllerInterface interface.
219
  $entity_info['node']['controllers']['storage'] = 'Drupal\mymodule\MyCustomNodeStorageController';
220 221
}

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
/**
 * Act on a newly created entity.
 *
 * This hook runs after a new entity object has just been instantiated. It can
 * be used to set initial values, e.g. to provide defaults.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 */
function hook_entity_create(\Drupal\Core\Entity\EntityInterface $entity) {
  // @todo Remove the check for EntityNG once all entity types have been
  //   converted to it.
  if (!isset($entity->foo) && ($entity instanceof \Drupal\Core\Entity\EntityNG)) {
    $entity->foo->value = 'some_initial_value';
  }
}

239 240 241 242 243 244
/**
 * Act on entities when loaded.
 *
 * This is a generic load hook called for all entity types loaded via the
 * entity API.
 *
245
 * @param array $entities
246
 *   The entities keyed by entity ID.
247
 * @param string $entity_type
248 249
 *   The type of entities being loaded (i.e. node, user, comment).
 */
250
function hook_entity_load($entities, $entity_type) {
251
  foreach ($entities as $entity) {
252
    $entity->foo = mymodule_add_something($entity);
253 254 255 256 257 258
  }
}

/**
 * Act on an entity before it is about to be created or updated.
 *
259
 * @param Drupal\Core\Entity\EntityInterface $entity
260 261
 *   The entity object.
 */
262
function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
263 264 265 266 267 268
  $entity->changed = REQUEST_TIME;
}

/**
 * Act on entities when inserted.
 *
269
 * @param Drupal\Core\Entity\EntityInterface $entity
270 271
 *   The entity object.
 */
272
function hook_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
273 274 275
  // Insert the new entity into a fictional table of all entities.
  db_insert('example_entity')
    ->fields(array(
276 277
      'type' => $entity->entityType(),
      'id' => $entity->id(),
278 279 280 281 282 283 284 285 286
      'created' => REQUEST_TIME,
      'updated' => REQUEST_TIME,
    ))
    ->execute();
}

/**
 * Act on entities when updated.
 *
287
 * @param Drupal\Core\Entity\EntityInterface $entity
288 289
 *   The entity object.
 */
290
function hook_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
291 292 293 294 295
  // Update the entity's entry in a fictional table of all entities.
  db_update('example_entity')
    ->fields(array(
      'updated' => REQUEST_TIME,
    ))
296 297
    ->condition('type', $entity->entityType())
    ->condition('id', $entity->id())
298 299 300 301
    ->execute();
}

/**
302 303 304
 * Act before entity deletion.
 *
 * This hook runs after the entity type-specific predelete hook.
305
 *
306
 * @param Drupal\Core\Entity\EntityInterface $entity
307 308
 *   The entity object for the entity that is about to be deleted.
 */
309
function hook_entity_predelete(Drupal\Core\Entity\EntityInterface $entity) {
310 311
  // Count references to this entity in a custom table before they are removed
  // upon entity deletion.
312 313
  $id = $entity->id();
  $type = $entity->entityType();
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
  $count = db_select('example_entity_data')
    ->condition('type', $type)
    ->condition('id', $id)
    ->countQuery()
    ->execute()
    ->fetchField();

  // Log the count in a table that records this statistic for deleted entities.
  $ref_count_record = (object) array(
    'count' => $count,
    'type' => $type,
    'id' => $id,
  );
  drupal_write_record('example_deleted_entity_statistics', $ref_count_record);
}

/**
 * Respond to entity deletion.
 *
 * This hook runs after the entity type-specific delete hook.
 *
335
 * @param Drupal\Core\Entity\EntityInterface $entity
336
 *   The entity object for the entity that has been deleted.
337
 */
338
function hook_entity_delete(Drupal\Core\Entity\EntityInterface $entity) {
339 340
  // Delete the entity's entry from a fictional table of all entities.
  db_delete('example_entity')
341 342
    ->condition('type', $entity->entityType())
    ->condition('id', $entity->id())
343 344 345 346
    ->execute();
}

/**
347
 * Alter or execute an Drupal\Core\Entity\Query\EntityQueryInterface.
348
 *
349
 * @param \Drupal\Core\Entity\Query\QueryInterface $query
350 351 352 353 354 355 356
 *   Note the $query->altered attribute which is TRUE in case the query has
 *   already been altered once. This happens with cloned queries.
 *   If there is a pager, then such a cloned query will be executed to count
 *   all elements. This query can be detected by checking for
 *   ($query->pager && $query->count), allowing the driver to return 0 from
 *   the count query and disable the pager.
 */
357 358
function hook_entity_query_alter(\Drupal\Core\Entity\Query\QueryInterface $query) {
  // @todo: code example.
359 360 361 362 363
}

/**
 * Act on entities being assembled before rendering.
 *
364
 * @param \Drupal\Core\Entity\EntityInterface $entity
365
 *   The entity object.
366 367 368
 * @param \Drupal\entity\Plugin\Core\Entity\EntityDisplay $display
 *   The entity_display object holding the display options configured for the
 *   entity components.
369 370 371 372 373 374 375 376 377 378 379 380 381 382
 * @param $view_mode
 *   The view mode the entity is rendered in.
 * @param $langcode
 *   The language code used for rendering.
 *
 * The module may add elements to $entity->content prior to rendering. The
 * structure of $entity->content is a renderable array as expected by
 * drupal_render().
 *
 * @see hook_entity_view_alter()
 * @see hook_comment_view()
 * @see hook_node_view()
 * @see hook_user_view()
 */
383 384 385 386 387 388 389 390 391 392
function hook_entity_view(\Drupal\Core\Entity\EntityInterface $entity, \Drupal\entity\Plugin\Core\Entity\EntityDisplay $display, $view_mode, $langcode) {
  // Only do the extra work if the component is configured to be displayed.
  // This assumes a 'mymodule_addition' extra field has been defined for the
  // entity bundle in hook_field_extra_fields().
  if ($display->getComponent('mymodule_addition')) {
    $entity->content['mymodule_addition'] = array(
      '#markup' => mymodule_addition($entity),
      '#theme' => 'mymodule_my_additional_field',
    );
  }
393 394 395 396 397 398 399 400 401 402 403
}

/**
 * Alter the results of ENTITY_view().
 *
 * This hook is called after the content has been assembled in a structured
 * array and may be used for doing processing which requires that the complete
 * entity content structure has been built.
 *
 * If a module wishes to act on the rendered HTML of the entity rather than the
 * structured content array, it may use this hook to add a #post_render
404 405
 * callback. Alternatively, it could also implement hook_preprocess_HOOK() for
 * the particular entity type template, if there is one (e.g., node.tpl.php).
406 407 408 409
 * See drupal_render() and theme() for details.
 *
 * @param $build
 *   A renderable array representing the entity content.
410
 * @param Drupal\Core\Entity\EntityInterface $entity
411
 *   The entity object being rendered.
412 413 414
 * @param \Drupal\entity\Plugin\Core\Entity\EntityDisplay $display
 *   The entity_display object holding the display options configured for the
 *   entity components.
415 416 417 418 419 420 421
 *
 * @see hook_entity_view()
 * @see hook_comment_view_alter()
 * @see hook_node_view_alter()
 * @see hook_taxonomy_term_view_alter()
 * @see hook_user_view_alter()
 */
422
function hook_entity_view_alter(&$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\entity\Plugin\Core\Entity\EntityDisplay $display) {
423 424 425 426 427 428 429 430 431 432 433 434 435
  if ($build['#view_mode'] == 'full' && isset($build['an_additional_field'])) {
    // Change its weight.
    $build['an_additional_field']['#weight'] = -10;

    // Add a #post_render callback to act on the rendered HTML of the entity.
    $build['#post_render'][] = 'my_module_node_post_render';
  }
}

/**
 * Act on entities as they are being prepared for view.
 *
 * Allows you to operate on multiple entities as they are being prepared for
436
 * view. Only use this if attaching the data during the entity loading phase
437 438
 * is not appropriate, for example when attaching other 'entity' style objects.
 *
439 440
 * @param string $entity_type
 *   The type of entities being viewed (i.e. node, user, comment).
441 442 443 444 445 446 447
 * @param array $entities
 *   The entities keyed by entity ID.
 * @param array $display
 *   The array of entity_display objects holding the display options configured
 *   for the entity components, keyed by bundle name.
 * @param string $view_mode
 *   The view mode.
448
 */
449
function hook_entity_prepare_view($entity_type, array $entities, array $displays, $view_mode) {
450
  // Load a specific node into the user object for later theming.
451
  if (!empty($entities) && $entity_type == 'user') {
452 453 454 455 456 457 458 459 460 461 462 463 464 465
    // Only do the extra work if the component is configured to be
    // displayed. This assumes a 'mymodule_addition' extra field has been
    // defined for the entity bundle in hook_field_extra_fields().
    $ids = array();
    foreach ($entities as $id => $entity) {
      if ($displays[$entity->bundle()]->getComponent('mymodule_addition')) {
        $ids[] = $id;
      }
    }
    if ($ids) {
      $nodes = mymodule_get_user_nodes($ids);
      foreach ($ids as $id) {
        $entities[$id]->user_node = $nodes[$id];
      }
466 467 468
    }
  }
}
469 470 471 472 473 474

/**
 * Change the view mode of an entity that is being displayed.
 *
 * @param string $view_mode
 *   The view_mode that is to be used to display the entity.
475
 * @param Drupal\Core\Entity\EntityInterface $entity
476 477 478 479 480
 *   The entity that is being viewed.
 * @param array $context
 *   Array with additional context information, currently only contains the
 *   langcode the entity is viewed in.
 */
481
function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
482 483 484 485 486
  // For nodes, change the view mode when it is teaser.
  if ($entity->entityType() == 'node' && $view_mode == 'teaser') {
    $view_mode = 'my_custom_view_mode';
  }
}
487

488 489 490 491 492 493 494 495 496 497 498 499
/**
 * Alters the settings used for displaying an entity.
 *
 * @param \Drupal\entity\Plugin\Core\Entity\EntityDisplay $display
 *   The entity_display object that will be used to display the entity
 *   components.
 * @param array $context
 *   An associative array containing:
 *   - entity_type: The entity type, e.g., 'node' or 'user'.
 *   - bundle: The bundle, e.g., 'page' or 'article'.
 *   - view_mode: The view mode, e.g. 'full', 'teaser'...
 */
500
function hook_entity_display_alter(\Drupal\entity\Plugin\Core\Entity\EntityDisplay $display, array $context) {
501 502
  // Leave field labels out of the search index.
  if ($context['entity_type'] == 'node' && $context['view_mode'] == 'search_index') {
503 504 505 506
    foreach ($display->getComponents() as $name => $options) {
      if (isset($options['label'])) {
        $options['label'] = 'hidden';
        $display->setComponent($name, $options);
507 508 509 510 511
      }
    }
  }
}

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
/**
 * Define custom entity properties.
 *
 * @param string $entity_type
 *   The entity type for which to define entity properties.
 *
 * @return array
 *   An array of property information having the following optional entries:
 *   - definitions: An array of property definitions to add all entities of this
 *     type, keyed by property name. See
 *     Drupal\Core\TypedData\TypedDataManager::create() for a list of supported
 *     keys in property definitions.
 *   - optional: An array of property definitions for optional properties keyed
 *     by property name. Optional properties are properties that only exist for
 *     certain bundles of the entity type.
 *   - bundle map: An array keyed by bundle name containing the names of
 *     optional properties that entities of this bundle have.
 *
 * @see Drupal\Core\TypedData\TypedDataManager::create()
 * @see hook_entity_field_info_alter()
 * @see Drupal\Core\Entity\StorageControllerInterface::getPropertyDefinitions()
 */
function hook_entity_field_info($entity_type) {
  if (mymodule_uses_entity_type($entity_type)) {
    $info = array();
    $info['definitions']['mymodule_text'] = array(
      'type' => 'string_item',
      'list' => TRUE,
      'label' => t('The text'),
      'description' => t('A text property added by mymodule.'),
      'computed' => TRUE,
      'class' => '\Drupal\mymodule\EntityComputedText',
    );
    if ($entity_type == 'node') {
      // Add a property only to entities of the 'article' bundle.
      $info['optional']['mymodule_text_more'] = array(
        'type' => 'string_item',
        'list' => TRUE,
        'label' => t('More text'),
        'computed' => TRUE,
        'class' => '\Drupal\mymodule\EntityComputedMoreText',
      );
      $info['bundle map']['article'][0] = 'mymodule_text_more';
    }
    return $info;
  }
}

/**
 * Alter defined entity properties.
 *
 * @param array $info
 *   The property info array as returned by hook_entity_field_info().
 * @param string $entity_type
 *   The entity type for which entity properties are defined.
 *
 * @see hook_entity_field_info()
 */
function hook_entity_field_info_alter(&$info, $entity_type) {
  if (!empty($info['definitions']['mymodule_text'])) {
    // Alter the mymodule_text property to use a custom class.
    $info['definitions']['mymodule_text']['class'] = '\Drupal\anothermodule\EntityComputedText';
  }
}
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

/**
 * Control access to fields.
 *
 * This hook is invoked from \Drupal\Core\Entity\Field\Type\Field::access() to
 * let modules grant or deny operations on fields.
 *
 * @param string $operation
 *   The operation to be performed. See
 *   \Drupal\Core\TypedData\AccessibleInterface::access() for possible values.
 * @param \Drupal\Core\Entity\Field\Type\Field $field
 *   The entity field object on which the operation is to be performed.
 * @param \Drupal\user\Plugin\Core\Entity\User $account
 *   The user account to check.
 *
 * @return bool|NULL
 *   TRUE if access should be allowed, FALSE if access should be denied and NULL
 *   if the implementation has no opinion.
 */
function hook_entity_field_access($operation, $field, $account) {
  if ($field->getName() == 'field_of_interest' && $operation == 'update') {
    return user_access('update field of interest', $account);
  }
}

/**
 * Alters the default access behaviour for a given field.
 *
 * Use this hook to override access grants from another module. Note that the
 * original default access flag is masked under the ':default' key.
 *
 * @param array $grants
 *   An array of grants gathered by hook_entity_field_access(). The array is
 *   keyed by the module that defines the field's access control; the values are
 *   grant responses for each module (Boolean or NULL).
 * @param array $context
 *   Context array on the performed operation with the following keys:
 *   - operation: The operation to be performed (string).
 *   - field: The entity field object (\Drupal\Core\Entity\Field\Type\Field).
 *   - account: The user account to check access for
 *     (Drupal\user\Plugin\Core\Entity\User).
 */
function hook_entity_field_access_alter(array &$grants, array $context) {
  $field = $context['field'];
  if ($field->getName() == 'field_of_interest' && $grants['node'] === FALSE) {
    // Override node module's restriction to no opinion. We don't want to
    // provide our own access hook, we only want to take out node module's part
    // in the access handling of this field. We also don't want to switch node
    // module's grant to TRUE, because the grants of other modules should still
    // decide on their own if this field is accessible or not.
    $grants['node'] = NULL;
  }
}