entity.api.php 82.6 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Hooks and documentation related to entities.
6 7
 */

8
use Drupal\Core\Access\AccessResult;
9
use Drupal\Core\Entity\ContentEntityInterface;
10
use Drupal\Core\Entity\DynamicallyFieldableEntityStorageInterface;
11
use Drupal\Core\Field\BaseFieldDefinition;
12
use Drupal\Core\Render\Element;
13
use Drupal\language\Entity\ContentLanguageSettings;
14
use Drupal\node\Entity\NodeType;
15

16 17 18 19 20 21 22 23 24
/**
 * @defgroup entity_crud Entity CRUD, editing, and view hooks
 * @{
 * Hooks used in various entity operations.
 *
 * Entity create, read, update, and delete (CRUD) operations are performed by
 * entity storage classes; see the
 * @link entity_api Entity API topic @endlink for more information. Most
 * entities use or extend the default classes:
25
 * \Drupal\Core\Entity\Sql\SqlContentEntityStorage for content entities, and
26 27 28 29 30 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 65 66 67 68 69 70
 * \Drupal\Core\Config\Entity\ConfigEntityStorage for configuration entities.
 * For these entities, there is a set of hooks that is invoked for each
 * CRUD operation, which module developers can implement to affect these
 * operations; these hooks are actually invoked from methods on
 * \Drupal\Core\Entity\EntityStorageBase.
 *
 * For content entities, viewing and rendering are handled by a view builder
 * class; see the @link entity_api Entity API topic @endlink for more
 * information. Most view builders extend or use the default class
 * \Drupal\Core\Entity\EntityViewBuilder.
 *
 * Entity editing (including adding new entities) is handled by entity form
 * classes; see the @link entity_api Entity API topic @endlink for more
 * information. Most entity editing forms extend base classes
 * \Drupal\Core\Entity\EntityForm or \Drupal\Core\Entity\ContentEntityForm.
 * Note that many other operations, such as confirming deletion of entities,
 * also use entity form classes.
 *
 * This topic lists all of the entity CRUD and view operations, and the hooks
 * and other operations that are invoked (in order) for each operation. Some
 * notes:
 * - Whenever an entity hook is invoked, there is both a type-specific entity
 *   hook, and a generic entity hook. For instance, during a create operation on
 *   a node, first hook_node_create() and then hook_entity_create() would be
 *   invoked.
 * - The entity-type-specific hooks are represented in the list below as
 *   hook_ENTITY_TYPE_... (hook_ENTITY_TYPE_create() in this example). To
 *   implement one of these hooks for an entity whose machine name is "foo",
 *   define a function called mymodule_foo_create(), for instance. Also note
 *   that the entity or array of entities that are passed into a specific-type
 *   hook are of the specific entity class, not the generic Entity class, so in
 *   your implementation, you can make the $entity argument something like $node
 *   and give it a specific type hint (which should normally be to the specific
 *   interface, such as \Drupal\Node\NodeInterface for nodes).
 * - $storage in the code examples is assumed to be an entity storage
 *   class. See the @link entity_api Entity API topic @endlink for
 *   information on how to instantiate the correct storage class for an
 *   entity type.
 * - $view_builder in the code examples is assumed to be an entity view builder
 *   class. See the @link entity_api Entity API topic @endlink for
 *   information on how to instantiate the correct view builder class for
 *   an entity type.
 * - During many operations, static methods are called on the entity class,
 *   which implements \Drupal\Entity\EntityInterface.
 *
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 110 111 112 113 114 115 116 117 118 119 120 121
 * @section entities_revisions_translations Entities, revisions and translations
 * A content entity can have multiple stored variants: based on its definition,
 * it can be revisionable, translatable, or both.
 *
 * A revisionable entity can keep track of the changes that affect its data. In
 * fact all previous revisions of the entity can be stored and made available as
 * "historical" information. The "default" revision is the canonical variant of
 * the entity, the one that is loaded when no specific revision is requested.
 * Only changes to the default revision may be performed without triggering the
 * creation of a new revision, in any other case revision data is not supposed
 * to change. Aside from historical revisions, there can be "pending" revisions,
 * that contain changes that did not make their way into the default revision.
 * Typically these revisions contain data that is waiting for some form of
 * approval, before being accepted as canonical.
 * @see \Drupal\Core\Entity\RevisionableInterface
 * @see \Drupal\Core\Entity\RevisionableStorageInterface
 *
 * A translatable entity can contain multiple translations of the same content.
 * Content entity data is stored via fields, and each field can have one version
 * for each enabled language. Some fields may be defined as untranslatable,
 * which means that their values are shared among all translations. The
 * "default" translation is the canonical variant of the entity, the one whose
 * content will be accessible in the entity field data. Other translations
 * can be instantiated from the default one. Every translation has an "active
 * language" that is used to determine which field translation values should be
 * handled. Typically the default translation's active language is the language
 * of the content that was originally entered and served as source for the other
 * translations.
 * @see \Drupal\Core\Entity\TranslatableInterface
 * @see \Drupal\Core\Entity\TranslatableStorageInterface
 *
 * An entity that is both revisionable and translatable has all the features
 * described above: every revision can contain one or more translations. The
 * canonical variant of the entity is the default translation of the default
 * revision. Any revision will be initially loaded as the default translation,
 * the other revision translations can be instantiated from this one. If a
 * translation has changes in a certain revision, the translation is considered
 * "affected" by that revision, and will be flagged as such via the
 * "revision_translation_affected" field. With the built-in UI, every time a new
 * revision is saved, the changes for the edited translations will be stored,
 * while all field values for the other translations will be copied as-is.
 * However, if multiple translations of the default revision are being
 * subsequently modified without creating a new revision when saving, they will
 * all be affected by the default revision. Additionally, all revision
 * translations will be affected when saving a revision containing changes for
 * untranslatable fields. On the other hand, pending revisions are not supposed
 * to contain multiple affected translations, even when they are being
 * manipulated via the API.
 * @see \Drupal\Core\Entity\TranslatableRevisionableInterface
 * @see \Drupal\Core\Entity\TranslatableRevisionableStorageInterface
 *
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
 * @section create Create operations
 * To create an entity:
 * @code
 * $entity = $storage->create();
 *
 * // Add code here to set properties on the entity.
 *
 * // Until you call save(), the entity is just in memory.
 * $entity->save();
 * @endcode
 * There is also a shortcut method on entity classes, which creates an entity
 * with an array of provided property values: \Drupal\Core\Entity::create().
 *
 * Hooks invoked during the create operation:
 * - hook_ENTITY_TYPE_create()
 * - hook_entity_create()
138 139 140 141
 * - When handling content entities, if a new translation is added to the entity
 *   object:
 *   - hook_ENTITY_TYPE_translation_create()
 *   - hook_entity_translation_create()
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
 *
 * See @ref save below for the save portion of the operation.
 *
 * @section load Read/Load operations
 * To load (read) a single entity:
 * @code
 * $entity = $storage->load($id);
 * @endcode
 * To load multiple entities:
 * @code
 * $entities = $storage->loadMultiple($ids);
 * @endcode
 * Since load() calls loadMultiple(), these are really the same operation.
 * Here is the order of hooks and other operations that take place during
 * entity loading:
 * - Entity is loaded from storage.
 * - postLoad() is called on the entity class, passing in all of the loaded
 *   entities.
 * - hook_entity_load()
 * - hook_ENTITY_TYPE_load()
 *
 * When an entity is loaded, normally the default entity revision is loaded.
 * It is also possible to load a different revision, for entities that support
 * revisions, with this code:
 * @code
 * $entity = $storage->loadRevision($revision_id);
 * @endcode
 * This involves the same hooks and operations as regular entity loading.
 *
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 198 199
 * The "latest revision" of an entity is the most recently created one,
 * regardless of it being default or pending. If the entity is translatable,
 * revision translations are not taken into account either. In other words, any
 * time a new revision is created, that becomes the latest revision for the
 * entity overall, regardless of the affected translations. To load the latest
 * revision of an entity:
 * @code
 * $revision_id = $storage->getLatestRevisionId($entity_id);
 * $entity = $storage->loadRevision($revision_id);
 * @endcode
 * As usual, if the entity is translatable, this code instantiates into $entity
 * the default translation of the revision, even if the latest revision contains
 * only changes to a different translation:
 * @code
 * $is_default = $entity->isDefaultTranslation(); // returns TRUE
 * @endcode
 *
 * The "latest translation-affected revision" is the most recently created one
 * that affects the specified translation. For example, when a new revision
 * introducing some changes to an English translation is saved, that becomes the
 * new "latest revision". However, if an existing Italian translation was not
 * affected by those changes, then the "latest translation-affected revision"
 * for Italian remains what it was. To load the Italian translation at its
 * latest translation-affected revision:
 * @code
 * $revision_id = $storage->getLatestTranslationAffectedRevisionId($entity_id, 'it');
 * $it_translation = $storage->loadRevision($revision_id)->getTranslation('it');
 * @endcode
 *
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
 * @section save Save operations
 * To update an existing entity, you will need to load it, change properties,
 * and then save; as described above, when creating a new entity, you will also
 * need to save it. Here is the order of hooks and other events that happen
 * during an entity save:
 * - preSave() is called on the entity object, and field objects.
 * - hook_ENTITY_TYPE_presave()
 * - hook_entity_presave()
 * - Entity is saved to storage.
 * - For updates on content entities, if there is a translation added that
 *   was not previously present:
 *   - hook_ENTITY_TYPE_translation_insert()
 *   - hook_entity_translation_insert()
 * - For updates on content entities, if there was a translation removed:
 *   - hook_ENTITY_TYPE_translation_delete()
 *   - hook_entity_translation_delete()
 * - postSave() is called on the entity object.
 * - hook_ENTITY_TYPE_insert() (new) or hook_ENTITY_TYPE_update() (update)
 * - hook_entity_insert() (new) or hook_entity_update() (update)
 *
 * Some specific entity types invoke hooks during preSave() or postSave()
 * operations. Examples:
222
 * - Field configuration preSave(): hook_field_storage_config_update_forbid()
223 224
 * - Node postSave(): hook_node_access_records() and
 *   hook_node_access_records_alter()
225 226
 * - Config entities that are acting as entity bundles in postSave():
 *   hook_entity_bundle_create()
227 228 229
 * - Comment: hook_comment_publish() and hook_comment_unpublish() as
 *   appropriate.
 *
230 231 232 233
 * Note that all translations available for the entity are stored during a save
 * operation. When saving a new revision, a copy of every translation is stored,
 * regardless of it being affected by the revision.
 *
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
 * @section edit Editing operations
 * When an entity's add/edit form is used to add or edit an entity, there
 * are several hooks that are invoked:
 * - hook_entity_prepare_form()
 * - hook_ENTITY_TYPE_prepare_form()
 * - hook_entity_form_display_alter() (for content entities only)
 *
 * @section delete Delete operations
 * To delete one or more entities, load them and then delete them:
 * @code
 * $entities = $storage->loadMultiple($ids);
 * $storage->delete($entities);
 * @endcode
 *
 * During the delete operation, the following hooks and other events happen:
 * - preDelete() is called on the entity class.
 * - hook_ENTITY_TYPE_predelete()
 * - hook_entity_predelete()
 * - Entity and field information is removed from storage.
 * - postDelete() is called on the entity class.
 * - hook_ENTITY_TYPE_delete()
 * - hook_entity_delete()
 *
 * Some specific entity types invoke hooks during the delete process. Examples:
 * - Entity bundle postDelete(): hook_entity_bundle_delete()
 *
 * Individual revisions of an entity can also be deleted:
 * @code
 * $storage->deleteRevision($revision_id);
 * @endcode
 * This operation invokes the following operations and hooks:
 * - Revision is loaded (see @ref load above).
 * - Revision and field information is removed from the database.
 * - hook_ENTITY_TYPE_revision_delete()
 * - hook_entity_revision_delete()
 *
 * @section view View/render operations
 * To make a render array for a loaded entity:
 * @code
 * // You can omit the language ID if the default language is being used.
274
 * $build = $view_builder->view($entity, 'view_mode_name', $language->getId());
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
 * @endcode
 * You can also use the viewMultiple() method to view multiple entities.
 *
 * Hooks invoked during the operation of building a render array:
 * - hook_entity_view_mode_alter()
 * - hook_ENTITY_TYPE_build_defaults_alter()
 * - hook_entity_build_defaults_alter()
 *
 * View builders for some types override these hooks, notably:
 * - The Tour view builder does not invoke any hooks.
 * - The Block view builder invokes hook_block_view_alter() and
 *   hook_block_view_BASE_BLOCK_ID_alter(). Note that in other view builders,
 *   the view alter hooks are run later in the process.
 *
 * During the rendering operation, the default entity viewer runs the following
 * hooks and operations in the pre-render step:
 * - hook_entity_view_display_alter()
 * - hook_entity_prepare_view()
 * - Entity fields are loaded, and render arrays are built for them using
 *   their formatters.
 * - hook_entity_display_build_alter()
 * - hook_ENTITY_TYPE_view()
 * - hook_entity_view()
 * - hook_ENTITY_TYPE_view_alter()
 * - hook_entity_view_alter()
 *
 * Some specific builders have specific hooks:
 * - The Node view builder invokes hook_node_links_alter().
 * - The Comment view builder invokes hook_comment_links_alter().
 *
 * After this point in rendering, the theme system takes over. See the
 * @link theme_render Theme system and render API topic @endlink for more
 * information.
 *
 * @section misc Other entity hooks
 * Some types of entities invoke hooks for specific operations:
 * - Searching nodes:
 *   - hook_ranking()
 *   - Query is executed to find matching nodes
 *   - Resulting node is loaded
 *   - Node render array is built
 *   - comment_node_update_index() is called (this adds "N comments" text)
 *   - hook_node_search_result()
 * - Search indexing nodes:
 *   - Node is loaded
 *   - Node render array is built
 *   - hook_node_update_index()
 * @}
 */

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
/**
 * @defgroup entity_api Entity API
 * @{
 * Describes how to define and manipulate content and configuration entities.
 *
 * Entities, in Drupal, are objects that are used for persistent storage of
 * content and configuration information. See the
 * @link info_types Information types topic @endlink for an overview of the
 * different types of information, and the
 * @link config_api Configuration API topic @endlink for more about the
 * configuration API.
 *
 * Each entity is an instance of a particular "entity type". Some content entity
 * types have sub-types, which are known as "bundles", while for other entity
 * types, there is only a single bundle. For example, the Node content entity
 * type, which is used for the main content pages in Drupal, has bundles that
 * are known as "content types", while the User content type, which is used for
 * user accounts, has only one bundle.
 *
 * The sections below have more information about entities and the Entity API;
345 346
 * for more detailed information, see
 * https://www.drupal.org/developing/api/entity.
347 348 349 350 351 352 353 354
 *
 * @section define Defining an entity type
 * Entity types are defined by modules, using Drupal's Plugin API (see the
 * @link plugin_api Plugin API topic @endlink for more information about plugins
 * in general). Here are the steps to follow to define a new entity type:
 * - Choose a unique machine name, or ID, for your entity type. This normally
 *   starts with (or is the same as) your module's machine name. It should be
 *   as short as possible, and may not exceed 32 characters.
355 356
 * - Define an interface for your entity's get/set methods, usually extending
 *   either \Drupal\Core\Config\Entity\ConfigEntityInterface or
357 358 359 360 361
 *   \Drupal\Core\Entity\ContentEntityInterface.
 * - Define a class for your entity, implementing your interface and extending
 *   either \Drupal\Core\Config\Entity\ConfigEntityBase or
 *   \Drupal\Core\Entity\ContentEntityBase, with annotation for
 *   \@ConfigEntityType or \@ContentEntityType in its documentation block.
362 363 364 365 366
 *   If you are defining a content entity type, it is recommended to extend the
 *   \Drupal\Core\Entity\EditorialContentEntityBase base class in order to get
 *   out-of-the-box support for Entity API's revisioning and publishing
 *   features, which will allow your entity type to be used with Drupal's
 *   editorial workflow provided by the Content Moderation module.
367 368 369 370 371
 * - In the annotation, the 'id' property gives the entity type ID, and the
 *   'label' property gives the human-readable name of the entity type. If you
 *   are defining a content entity type that uses bundles, the 'bundle_label'
 *   property gives the human-readable name to use for a bundle of this entity
 *   type (for example, "Content type" for the Node entity).
372 373
 * - The annotation will refer to several handler classes, which you will also
 *   need to define:
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
 *   - list_builder: Define a class that extends
 *     \Drupal\Core\Config\Entity\ConfigEntityListBuilder (for configuration
 *     entities) or \Drupal\Core\Entity\EntityListBuilder (for content
 *     entities), to provide an administrative overview for your entities.
 *   - add and edit forms, or default form: Define a class (or two) that
 *     extend(s) \Drupal\Core\Entity\EntityForm to provide add and edit forms
 *     for your entities. For content entities, base class
 *     \Drupal\Core\Entity\ContentEntityForm is a better starting point.
 *   - delete form: Define a class that extends
 *     \Drupal\Core\Entity\EntityConfirmFormBase to provide a delete
 *     confirmation form for your entities.
 *   - view_builder: For content entities and config entities that need to be
 *     viewed, define a class that implements
 *     \Drupal\Core\Entity\EntityViewBuilderInterface (usually extending
 *     \Drupal\Core\Entity\EntityViewBuilder), to display a single entity.
 *   - translation: For translatable content entities (if the 'translatable'
390
 *     annotation property has value TRUE), define a class that extends
391 392
 *     \Drupal\content_translation\ContentTranslationHandler, to translate
 *     the content. Configuration translation is handled automatically by the
393
 *     Configuration Translation module, without the need of a handler class.
394
 *   - access: If your configuration entity has complex permissions, you might
395
 *     need an access control handling, implementing
396 397 398 399 400
 *     \Drupal\Core\Entity\EntityAccessControlHandlerInterface, but most
 *     entities can just use the 'admin_permission' annotation property
 *     instead. Note that if you are creating your own access control handler,
 *     you should override the checkAccess() and checkCreateAccess() methods,
 *     not access().
401 402
 *   - storage: A class implementing
 *     \Drupal\Core\Entity\EntityStorageInterface. If not specified, content
403
 *     entities will use \Drupal\Core\Entity\Sql\SqlContentEntityStorage, and
404 405
 *     config entities will use \Drupal\Core\Config\Entity\ConfigEntityStorage.
 *     You can extend one of these classes to provide custom behavior.
406
 *   - views_data: A class implementing \Drupal\views\EntityViewsDataInterface
407 408
 *     to provide views data for the entity type. You can autogenerate most of
 *     the views data by extending \Drupal\views\EntityViewsData.
409 410 411
 * - For content entities, the annotation will refer to a number of database
 *   tables and their fields. These annotation properties, such as 'base_table',
 *   'data_table', 'entity_keys', etc., are documented on
412
 *   \Drupal\Core\Entity\EntityType.
413 414 415 416 417
 * - For content entities that are displayed on their own pages, the annotation
 *   will refer to a 'uri_callback' function, which takes an object of the
 *   entity interface you have defined as its parameter, and returns routing
 *   information for the entity page; see node_uri() for an example. You will
 *   also need to add a corresponding route to your module's routing.yml file;
418
 *   see the entity.node.canonical route in node.routing.yml for an example, and see
419
 *   @ref sec_routes below for some notes.
420 421 422
 * - Optionally, instead of defining routes, routes can be auto generated by
 *   providing a route handler. See @ref sec_routes. Otherwise, define routes
 *   and links for the various URLs associated with the entity.
423
 *   These go into the 'links' annotation, with the link type as the key, and
424 425 426 427
 *   the path of this link template as the value. The corresponding route
 *   requires the following route name:
 *   "entity.$entity_type_id.$link_template_type". See @ref sec_routes below for
 *   some routing notes. Typical link types are:
428 429 430 431 432
 *   - canonical: Default link, either to view (if entities are viewed on their
 *     own pages) or edit the entity.
 *   - delete-form: Confirmation form to delete the entity.
 *   - edit-form: Editing form.
 *   - Other link types specific to your entity type can also be defined.
433 434 435 436 437
 * - If your content entity is fieldable, provide the 'field_ui_base_route'
 *   annotation property, giving the name of the route that the Manage Fields,
 *   Manage Display, and Manage Form Display pages from the Field UI module
 *   will be attached to. This is usually the bundle settings edit page, or an
 *   entity type settings page if there are no bundles.
438 439 440
 * - If your content entity has bundles, you will also need to define a second
 *   plugin to handle the bundles. This plugin is itself a configuration entity
 *   type, so follow the steps here to define it. The machine name ('id'
441 442 443 444 445 446 447
 *   annotation property) of this configuration entity class goes into the
 *   'bundle_entity_type' annotation property on the entity type class. For
 *   example, for the Node entity, the bundle class is
 *   \Drupal\node\Entity\NodeType, whose machine name is 'node_type'. This is
 *   the annotation property 'bundle_entity_type' on the
 *   \Drupal\node\Entity\Node class. Also, the
 *   bundle config entity type annotation must have a 'bundle_of' property,
448
 *   giving the machine name of the entity type it is acting as a bundle for.
449
 *   These machine names are considered permanent, they may not be renamed.
450 451 452
 * - Additional annotation properties can be seen on entity class examples such
 *   as \Drupal\node\Entity\Node (content) and \Drupal\user\Entity\Role
 *   (configuration). These annotation properties are documented on
453 454 455
 *   \Drupal\Core\Entity\EntityType.
 *
 * @section sec_routes Entity routes
456 457 458 459 460 461 462 463 464 465 466 467
 * Entity routes can be defined in *.routing.yml files, like any other route:
 * see the @link routing Routing API @endlink topic for more information.
 * Another option for entity routes is to use a route provider class, and
 * reference it in the annotations on the entity class: see the end of this
 * section for an example.
 *
 * It's possible to use both a YAML file and a provider class for entity
 * routes, at the same time. Avoid duplicating route names between the two:
 * if a duplicate route name is found in both locations, the one in the YAML
 * file takes precedence; regardless, such duplication can be confusing.
 *
 * Here's an example YAML route specification, for the block configure form:
468
 * @code
469
 * entity.block.edit_form:
470 471 472 473 474 475 476
 *   path: '/admin/structure/block/manage/{block}'
 *   defaults:
 *     _entity_form: 'block.default'
 *     _title: 'Configure block'
 *   requirements:
 *     _entity_access: 'block.update'
 * @endcode
477
 * Some notes on this example:
478 479 480 481 482 483
 * - path: The {block} in the path is a placeholder, which (for an entity) must
 *   always take the form of {machine_name_of_entity_type}. In the URL, the
 *   placeholder value will be the ID of an entity item. When the route is used,
 *   the entity system will load the corresponding entity item and pass it in as
 *   an object to the controller for the route.
 * - defaults: For entity form routes, use _entity_form rather than the generic
484
 *   _controller or _form. The value is composed of the entity type machine name
485 486 487 488
 *   and a form handler type from the entity annotation (see @ref define above
 *   more more on handlers and annotation). So, in this example, block.default
 *   refers to the 'default' form handler on the block entity type, whose
 *   annotation contains:
489
 *   @code
490
 *   handlers = {
491 492 493
 *     "form" = {
 *       "default" = "Drupal\block\BlockForm",
 *   @endcode
494 495 496 497
 * If instead of YAML you want to use a route provider class:
 * - \Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider provides canonical,
 *   edit-form, and delete-form routes.
 * - \Drupal\Core\Entity\Routing\AdminHtmlRouteProvider provides the same
498
 *   routes, set up to use the administrative theme for edit and delete pages.
499 500 501 502 503 504 505 506 507 508
 * - You can also create your own class, extending one of these two classes if
 *   you only want to modify their behaviour slightly.
 *
 * To register any route provider class, add lines like the following to your
 * entity class annotation:
 * @code
 * handlers = {
 *   "route_provider" = {
 *     "html" = "Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider",
 * @endcode
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
 *
 * @section bundle Defining a content entity bundle
 * For entity types that use bundles, such as Node (bundles are content types)
 * and Taxonomy (bundles are vocabularies), modules and install profiles can
 * define bundles by supplying default configuration in their config/install
 * directories. (See the @link config_api Configuration API topic @endlink for
 * general information about configuration.)
 *
 * There are several good examples of this in Drupal Core:
 * - The Forum module defines a content type in node.type.forum.yml and a
 *   vocabulary in taxonomy.vocabulary.forums.yml
 * - The Book module defines a content type in node.type.book.yml
 * - The Standard install profile defines Page and Article content types in
 *   node.type.page.yml and node.type.article.yml, a Tags vocabulary in
 *   taxonomy.vocabulary.tags.yml, and a Node comment type in
 *   comment.type.comment.yml. This profile's configuration is especially
 *   instructive, because it also adds several fields to the Article type, and
 *   it sets up view and form display modes for the node types.
 *
 * @section load_query Loading, querying, and rendering entities
 * To load entities, use the entity storage manager, which is an object
 * implementing \Drupal\Core\Entity\EntityStorageInterface that you can
 * retrieve with:
 * @code
 * $storage = \Drupal::entityManager()->getStorage('your_entity_type');
 * // Or if you have a $container variable:
 * $storage = $container->get('entity.manager')->getStorage('your_entity_type');
 * @endcode
 * Here, 'your_entity_type' is the machine name of your entity type ('id'
538 539
 * annotation property on the entity class), and note that you should use
 * dependency injection to retrieve this object if possible. See the
540 541 542 543 544 545 546 547 548 549
 * @link container Services and Dependency Injection topic @endlink for more
 * about how to properly retrieve services.
 *
 * To query to find entities to load, use an entity query, which is a object
 * implementing \Drupal\Core\Entity\Query\QueryInterface that you can retrieve
 * with:
 * @code
 * // Simple query:
 * $query = \Drupal::entityQuery('your_entity_type');
 * // Or, if you have a $container variable:
550 551
 * $storage = $container->get('entity_type.manager')->getStorage('your_entity_type');
 * $query = $storage->getQuery();
552
 * @endcode
553
 * If you need aggregation, there is an aggregate query available, which
554 555 556 557
 * implements \Drupal\Core\Entity\Query\QueryAggregateInterface:
 * @code
 * $query \Drupal::entityQueryAggregate('your_entity_type');
 * // Or:
558
 * $query = $storage->getAggregateQuery('your_entity_type');
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
 * @endcode
 *
 * In either case, you can then add conditions to your query, using methods
 * like condition(), exists(), etc. on $query; add sorting, pager, and range
 * if needed, and execute the query to return a list of entity IDs that match
 * the query.
 *
 * Here is an example, using the core File entity:
 * @code
 * $fids = Drupal::entityQuery('file')
 *   ->condition('status', FILE_STATUS_PERMANENT, '<>')
 *   ->condition('changed', REQUEST_TIME - $age, '<')
 *   ->range(0, 100)
 *   ->execute();
 * $files = $storage->loadMultiple($fids);
 * @endcode
 *
 * The normal way of viewing entities is by using a route, as described in the
 * sections above. If for some reason you need to render an entity in code in a
 * particular view mode, you can use an entity view builder, which is an object
 * implementing \Drupal\Core\Entity\EntityViewBuilderInterface that you can
 * retrieve with:
 * @code
 * $view_builder = \Drupal::entityManager()->getViewBuilder('your_entity_type');
 * // Or if you have a $container variable:
 * $view_builder = $container->get('entity.manager')->getViewBuilder('your_entity_type');
 * @endcode
 * Then, to build and render the entity:
 * @code
588 589 590
 * // You can omit the language ID, by default the current content language will
 * // be used. If no translation is available for the current language, fallback
 * // rules will be used.
591
 * $build = $view_builder->view($entity, 'view_mode_name', $language->getId());
592
 * // $build is a render array.
593
 * $rendered = \Drupal::service('renderer')->render($build);
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
 * @endcode
 *
 * @section sec_access Access checking on entities
 * Entity types define their access permission scheme in their annotation.
 * Access permissions can be quite complex, so you should not assume any
 * particular permission scheme. Instead, once you have an entity object
 * loaded, you can check for permission for a particular operation (such as
 * 'view') at the entity or field level by calling:
 * @code
 * $entity->access($operation);
 * $entity->nameOfField->access($operation);
 * @endcode
 * The interface related to access checking in entities and fields is
 * \Drupal\Core\Access\AccessibleInterface.
 *
609
 * The default entity access control handler invokes two hooks while checking
610 611 612 613 614 615 616 617 618 619 620 621 622 623
 * access on a single entity: hook_entity_access() is invoked first, and
 * then hook_ENTITY_TYPE_access() (where ENTITY_TYPE is the machine name
 * of the entity type). If no module returns a TRUE or FALSE value from
 * either of these hooks, then the entity's default access checking takes
 * place. For create operations (creating a new entity), the hooks that
 * are invoked are hook_entity_create_access() and
 * hook_ENTITY_TYPE_create_access() instead.
 *
 * The Node entity type has a complex system for determining access, which
 * developers can interact with. This is described in the
 * @link node_access Node access topic. @endlink
 *
 * @see i18n
 * @see entity_crud
624
 * @see \Drupal\Core\Entity\EntityManagerInterface::getTranslationFromContext()
625 626 627
 * @}
 */

628 629 630 631 632
/**
 * @addtogroup hooks
 * @{
 */

633 634 635 636 637 638 639 640
/**
 * Control entity operation access.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity to check access to.
 * @param string $operation
 *   The operation that is to be performed on $entity.
 * @param \Drupal\Core\Session\AccountInterface $account
641
 *   The account trying to access the entity.
642
 *
643
 * @return \Drupal\Core\Access\AccessResultInterface
644 645 646 647 648 649 650 651
 *   The access result. The final result is calculated by using
 *   \Drupal\Core\Access\AccessResultInterface::orIf() on the result of every
 *   hook_entity_access() and hook_ENTITY_TYPE_access() implementation, and the
 *   result of the entity-specific checkAccess() method in the entity access
 *   control handler. Be careful when writing generalized access checks shared
 *   between routing and entity checks: routing uses the andIf() operator. So
 *   returning an isNeutral() does not determine entity access at all but it
 *   always ends up denying access while routing.
652
 *
653
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
654 655 656 657
 * @see hook_entity_create_access()
 * @see hook_ENTITY_TYPE_access()
 *
 * @ingroup entity_api
658
 */
659
function hook_entity_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account) {
660
  // No opinion.
661
  return AccessResult::neutral();
662 663 664 665 666 667 668 669 670 671
}

/**
 * Control entity operation access for a specific entity type.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity to check access to.
 * @param string $operation
 *   The operation that is to be performed on $entity.
 * @param \Drupal\Core\Session\AccountInterface $account
672
 *   The account trying to access the entity.
673
 *
674
 * @return \Drupal\Core\Access\AccessResultInterface
675
 *   The access result. hook_entity_access() has detailed documentation.
676
 *
677
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
678 679 680 681
 * @see hook_ENTITY_TYPE_create_access()
 * @see hook_entity_access()
 *
 * @ingroup entity_api
682
 */
683
function hook_ENTITY_TYPE_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account) {
684
  // No opinion.
685
  return AccessResult::neutral();
686 687 688 689 690 691
}

/**
 * Control entity create access.
 *
 * @param \Drupal\Core\Session\AccountInterface $account
692
 *   The account trying to access the entity.
693
 * @param array $context
694
 *   An associative array of additional context values. By default it contains
695 696
 *   language and the entity type ID:
 *   - entity_type_id - the entity type ID.
697
 *   - langcode - the current language code.
698
 * @param string $entity_bundle
699
 *   The entity bundle name.
700
 *
701
 * @return \Drupal\Core\Access\AccessResultInterface
702
 *   The access result.
703
 *
704
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
705 706 707 708
 * @see hook_entity_access()
 * @see hook_ENTITY_TYPE_create_access()
 *
 * @ingroup entity_api
709
 */
710
function hook_entity_create_access(\Drupal\Core\Session\AccountInterface $account, array $context, $entity_bundle) {
711
  // No opinion.
712
  return AccessResult::neutral();
713 714 715 716 717 718
}

/**
 * Control entity create access for a specific entity type.
 *
 * @param \Drupal\Core\Session\AccountInterface $account
719
 *   The account trying to access the entity.
720
 * @param array $context
721 722 723
 *   An associative array of additional context values. By default it contains
 *   language:
 *   - langcode - the current language code.
724
 * @param string $entity_bundle
725
 *   The entity bundle name.
726
 *
727
 * @return \Drupal\Core\Access\AccessResultInterface
728
 *   The access result.
729
 *
730
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
731 732 733 734
 * @see hook_ENTITY_TYPE_access()
 * @see hook_entity_create_access()
 *
 * @ingroup entity_api
735
 */
736
function hook_ENTITY_TYPE_create_access(\Drupal\Core\Session\AccountInterface $account, array $context, $entity_bundle) {
737
  // No opinion.
738
  return AccessResult::neutral();
739 740
}

741
/**
742 743
 * Add to entity type definitions.
 *
744 745
 * Modules may implement this hook to add information to defined entity types,
 * as defined in \Drupal\Core\Entity\EntityTypeInterface.
746
 *
747 748 749
 * To alter existing information or to add information dynamically, use
 * hook_entity_type_alter().
 *
750
 * @param \Drupal\Core\Entity\EntityTypeInterface[] $entity_types
751 752 753 754
 *   An associative array of all entity type definitions, keyed by the entity
 *   type name. Passed by reference.
 *
 * @see \Drupal\Core\Entity\Entity
755
 * @see \Drupal\Core\Entity\EntityTypeInterface
756
 * @see hook_entity_type_alter()
757
 */
758 759
function hook_entity_type_build(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
760
  // Add a form for a custom node form without overriding the default
761
  // node form. To override the default node form, use hook_entity_type_alter().
762
  $entity_types['node']->setFormClass('mymodule_foo', 'Drupal\mymodule\NodeFooForm');
763 764
}

765 766 767 768 769 770 771 772
/**
 * Alter the entity type definitions.
 *
 * Modules may implement this hook to alter the information that defines an
 * entity type. All properties that are available in
 * \Drupal\Core\Entity\Annotation\EntityType and all the ones additionally
 * provided by modules can be altered here.
 *
773 774 775 776 777 778
 * Do not use this hook to add information to entity types, unless one of the
 * following is true:
 * - You are filling in default values.
 * - You need to dynamically add information only in certain circumstances.
 * - Your hook needs to run after hook_entity_type_build() implementations.
 * Use hook_entity_type_build() instead in all other cases.
779
 *
780
 * @param \Drupal\Core\Entity\EntityTypeInterface[] $entity_types
781 782 783 784 785 786
 *   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\EntityTypeInterface
 */
787 788
function hook_entity_type_alter(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
789
  // Set the controller class for nodes to an alternate implementation of the
790 791
  // Drupal\Core\Entity\EntityStorageInterface interface.
  $entity_types['node']->setStorageClass('Drupal\mymodule\MyCustomNodeStorage');
792 793
}

794 795 796 797 798 799
/**
 * 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.
 *
800 801
 * @see \Drupal\Core\Entity\EntityManagerInterface::getAllViewModes()
 * @see \Drupal\Core\Entity\EntityManagerInterface::getViewModes()
802 803
 */
function hook_entity_view_mode_info_alter(&$view_modes) {
804
  $view_modes['user']['full']['status'] = TRUE;
805 806 807 808 809 810 811 812 813 814 815 816 817
}

/**
 * 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.
818 819
 *   - translatable: (optional) A boolean value specifying whether this bundle
 *     has translation support enabled. Defaults to FALSE.
820
 *
821
 * @see \Drupal\Core\Entity\EntityTypeBundleInfo::getBundleInfo()
822 823 824
 * @see hook_entity_bundle_info_alter()
 */
function hook_entity_bundle_info() {
825
  $bundles['user']['user']['label'] = t('User');
826 827 828 829 830 831 832 833 834
  return $bundles;
}

/**
 * Alter the bundles for entity types.
 *
 * @param array $bundles
 *   An array of bundles, keyed first by entity type, then by bundle name.
 *
835
 * @see Drupal\Core\Entity\EntityTypeBundleInfo::getBundleInfo()
836 837 838 839
 * @see hook_entity_bundle_info()
 */
function hook_entity_bundle_info_alter(&$bundles) {
  $bundles['user']['user']['label'] = t('Full account');
840 841
}

842 843 844 845 846
/**
 * Act on entity_bundle_create().
 *
 * This hook is invoked after the operation has been performed.
 *
847
 * @param string $entity_type_id
848 849 850
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param string $bundle
 *   The name of the bundle.
851 852
 *
 * @see entity_crud
853
 */
854
function hook_entity_bundle_create($entity_type_id, $bundle) {
855 856
  // When a new bundle is created, the menu needs to be rebuilt to add the
  // Field UI menu item tabs.
857
  \Drupal::service('router.builder')->setRebuildNeeded();
858 859 860 861 862 863 864
}

/**
 * Act on entity_bundle_delete().
 *
 * This hook is invoked after the operation has been performed.
 *
865
 * @param string $entity_type_id
866 867 868
 *   The type of entity; for example, 'node' or 'user'.
 * @param string $bundle
 *   The bundle that was just deleted.
869 870
 *
 * @ingroup entity_crud
871
 */
872
function hook_entity_bundle_delete($entity_type_id, $bundle) {
873
  // Remove the settings associated with the bundle in my_module.settings.
874
  $config = \Drupal::config('my_module.settings');
875
  $bundle_settings = $config->get('bundle_settings');
876 877
  if (isset($bundle_settings[$entity_type_id][$bundle])) {
    unset($bundle_settings[$entity_type_id][$bundle]);
878 879 880 881
    $config->set('bundle_settings', $bundle_settings);
  }
}

882
/**
883
 * Acts when creating a new entity.
884
 *
885
 * This hook runs after a new entity object has just been instantiated.
886 887 888
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
889 890 891
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_create()
892 893
 */
function hook_entity_create(\Drupal\Core\Entity\EntityInterface $entity) {
894
  \Drupal::logger('example')->info('Entity created: @label', ['@label' => $entity->label()]);
895 896
}

897
/**
898
 * Acts when creating a new entity of a specific type.
899
 *
900
 * This hook runs after a new entity object has just been instantiated.
901 902 903 904 905 906 907 908
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @ingroup entity_crud
 * @see hook_entity_create()
 */
function hook_ENTITY_TYPE_create(\Drupal\Core\Entity\EntityInterface $entity) {
909
  \Drupal::logger('example')->info('ENTITY_TYPE created: @label', ['@label' => $entity->label()]);
910 911
}

912 913 914 915 916 917
/**
 * Act on entities when loaded.
 *
 * This is a generic load hook called for all entity types loaded via the
 * entity API.
 *
918 919 920 921
 * hook_entity_storage_load() should be used to load additional data for
 * content entities.
 *
 * @param \Drupal\Core\Entity\EntityInterface[] $entities
922
 *   The entities keyed by entity ID.
923
 * @param string $entity_type_id
924
 *   The type of entities being loaded (i.e. node, user, comment).
925 926 927
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_load()
928
 */
929
function hook_entity_load(array $entities, $entity_type_id) {
930
  foreach ($entities as $entity) {
931
    $entity->foo = mymodule_add_something($entity);
932 933 934 935
  }
}

/**
936 937 938 939 940 941 942 943 944 945 946 947 948 949
 * Act on entities of a specific type when loaded.
 *
 * @param array $entities
 *   The entities keyed by entity ID.
 *
 * @ingroup entity_crud
 * @see hook_entity_load()
 */
function hook_ENTITY_TYPE_load($entities) {
  foreach ($entities as $entity) {
    $entity->foo = mymodule_add_something($entity);
  }
}

950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
/**
 * Act on content entities when loaded from the storage.
 *
 * The results of this hook will be cached.
 *
 * @param \Drupal\Core\Entity\EntityInterface[] $entities
 *   The entities keyed by entity ID.
 * @param string $entity_type
 *   The type of entities being loaded (i.e. node, user, comment).
 *
 * @see hook_entity_load()
 */
function hook_entity_storage_load(array $entities, $entity_type) {
  foreach ($entities as $entity) {
    $entity->foo = mymodule_add_something_uncached($entity);
  }
}

/**
 * Act on content entities of a given type when loaded from the storage.
 *
 * The results of this hook will be cached if the entity type supports it.
 *
 * @param \Drupal\Core\Entity\EntityInterface[] $entities
 *   The entities keyed by entity ID.
 *
 * @see hook_entity_storage_load()
 */
function hook_ENTITY_TYPE_storage_load(array $entities) {
  foreach ($entities as $entity) {
    $entity->foo = mymodule_add_something_uncached($entity);
  }
}

984 985
/**
 * Act on an entity before it is created or updated.
986
 *
987 988 989
 * You can get the original entity object from $entity->original when it is an
 * update of the entity.
 *
990
 * @param \Drupal\Core\Entity\EntityInterface $entity
991
 *   The entity object.
992 993 994
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_presave()
995
 */
996
function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
997 998 999
  if ($entity instanceof ContentEntityInterface && $entity->isTranslatable()) {
    $route_match = \Drupal::routeMatch();
    \Drupal::service('content_translation.synchronizer')->synchronizeFields($entity, $entity->language()->getId(), $route_match->getParameter('source_langcode'));
1000 1001 1002 1003 1004 1005
  }
}

/**
 * Act on a specific type of entity before it is created or updated.
 *
1006 1007 1008
 * You can get the original entity object from $entity->original when it is an
 * update of the entity.
 *
1009 1010 1011 1012 1013 1014 1015 1016
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @ingroup entity_crud
 * @see hook_entity_presave()
 */
function hook_ENTITY_TYPE_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->isTranslatable()) {
1017 1018
    $route_match = \Drupal::routeMatch();
    \Drupal::service('content_translation.synchronizer')->synchronizeFields($entity, $entity->language()->getId(), $route_match->getParameter('source_langcode'));
1019
  }
1020 1021 1022
}

/**
1023 1024 1025 1026
 * Respond to creation of a new entity.
 *
 * This hook runs once the entity has been stored. Note that hook
 * implementations may not alter the stored entity data.
1027
 *
1028
 * @param \Drupal\Core\Entity\EntityInterface $entity
1029
 *   The entity object.
1030 1031 1032
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_insert()
1033
 */
1034
function hook_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
1035 1036
  // Insert the new entity into a fictional table of all entities.
  db_insert('example_entity')
1037
    ->fields([
1038
      'type' => $entity->getEntityTypeId(),
1039
      'id' => $entity->id(),
1040 1041
      'created' => REQUEST_TIME,
      'updated' => REQUEST_TIME,
1042
    ])
1043 1044 1045
    ->execute();
}

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
/**
 * Respond to creation of a new entity of a particular type.
 *
 * This hook runs once the entity has been stored. Note that hook
 * implementations may not alter the stored entity data.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @ingroup entity_crud
 * @see hook_entity_insert()
 */
function hook_ENTITY_TYPE_insert(Drupal\Core\Entity\EntityInterface $entity) {
  // Insert the new entity into a fictional table of this type of entity.
  db_insert('example_entity')
1061
    ->fields([
1062 1063 1064
      'id' => $entity->id(),
      'created' => REQUEST_TIME,
      'updated' => REQUEST_TIME,
1065
    ])
1066 1067 1068
    ->execute();
}

1069
/**
1070 1071 1072
 * Respond to updates to an entity.
 *
 * This hook runs once the entity storage has been updated. Note that hook
1073 1074
 * implementations may not alter the stored entity data. Get the original entity
 * object from $entity->original.
1075
 *
1076
 * @param \Drupal\Core\Entity\EntityInterface $entity
1077
 *   The entity object.
1078 1079 1080
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_update()
1081
 */
1082
function hook_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
1083 1084
  // Update the entity's entry in a fictional table of all entities.
  db_update('example_entity')
1085
    ->fields([
1086
      'updated' => REQUEST_TIME,
1087
    ])
1088
    ->condition('type', $entity->getEntityTypeId())
1089
    ->condition('id', $entity->id())
1090 1091 1092
    ->execute();
}

1093 1094 1095 1096
/**
 * Respond to updates to an entity of a particular type.
 *
 * This hook runs once the entity storage has been updated. Note that hook
1097 1098
 * implementations may not alter the stored entity data. Get the original entity
 * object from $entity->original.
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @ingroup entity_crud
 * @see hook_entity_update()
 */
function hook_ENTITY_TYPE_update(Drupal\Core\Entity\EntityInterface $entity) {
  // Update the entity's entry in a fictional table of this type of entity.
  db_update('example_entity')
1109
    ->fields([
1110
      'updated' => REQUEST_TIME,
1111
    ])
1112 1113 1114 1115
    ->condition('id', $entity->id())
    ->execute();
}

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
/**
 * Acts when creating a new entity translation.
 *
 * This hook runs after a new entity translation object has just been
 * instantiated.
 *
 * @param \Drupal\Core\Entity\EntityInterface $translation
 *   The entity object.
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_translation_create()
 */
function hook_entity_translation_create(\Drupal\Core\Entity\EntityInterface $translation) {
  \Drupal::logger('example')->info('Entity translation created: @label', ['@label' => $translation->label()]);
}

/**
 * Acts when creating a new entity translation of a specific type.
 *
 * This hook runs after a new entity translation object has just been
 * instantiated.
 *
 * @param \Drupal\Core\Entity\EntityInterface $translation
 *   The entity object.
 *
 * @ingroup entity_crud
 * @see hook_entity_translation_create()
 */
function hook_ENTITY_TYPE_translation_create(\Drupal\Core\Entity\EntityInterface $translation) {
  \Drupal::logger('example')->info('ENTITY_TYPE translation created: @label', ['@label' => $translation->label()]);
}

1148
/**
1149 1150 1151 1152
 * Respond to creation of a new entity translation.
 *
 * This hook runs once the entity translation has been stored. Note that hook
 * implementations may not alter the stored entity translation data.
1153 1154 1155
 *
 * @param \Drupal\Core\Entity\EntityInterface $translation
 *   The entity object of the translation just stored.
1156 1157 1158
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_translation_insert()
1159 1160
 */
function hook_entity_translation_insert(\Drupal\Core\Entity\EntityInterface $translation) {
1161
  $variables = [
1162
    '@language' => $translation->language()->getName(),
1163
    '@label' => $translation->getUntranslated()->label(),
1164
  ];
1165
  \Drupal::logger('example')->notice('The @language translation of @label has just been stored.', $variables);
1166 1167
}

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
/**
 * Respond to creation of a new entity translation of a particular type.
 *
 * This hook runs once the entity translation has been stored. Note that hook
 * implementations may not alter the stored entity translation data.
 *
 * @param \Drupal\Core\Entity\EntityInterface $translation
 *   The entity object of the translation just stored.
 *
 * @ingroup entity_crud
 * @see hook_entity_translation_insert()
 */
function hook_ENTITY_TYPE_translation_insert(\Drupal\Core\Entity\EntityInterface $translation) {
1181
  $variables = [
1182
    '@language' => $translation->language()->getName(),
1183
    '@label' => $translation->getUntranslated()->label(),
1184
  ];
1185 1186 1187
  \Drupal::logger('example')->notice('The @language translation of @label has just been stored.', $variables);
}

1188
/**
1189 1190 1191
 * Respond to entity translation deletion.
 *
 * This hook runs once the entity translation has been deleted from storage.
1192
 *
1193
 * @param \Drupal\Core\Entity\EntityInterface $translation
1194
 *   The original entity object.
1195 1196 1197
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_translation_delete()
1198 1199
 */
function hook_entity_translation_delete(\Drupal\Core\Entity\EntityInterface $translation) {
1200
  $variables = [
1201 1202
    '@language' => $translation->language()->getName(),
    '@label' => $translation->label(),
1203
  ];
1204
  \Drupal::logger('example')->notice('The @language translation of @label has just been deleted.', $variables);
1205 1206
}

1207 1208 1209 1210 1211
/**
 * Respond to entity translation deletion of a particular type.
 *
 * This hook runs once the entity translation has been deleted from storage.
 *
1212
 * @param \Drupal\Core\Entity\EntityInterface $translation
1213 1214 1215 1216 1217 1218
 *   The original entity object.
 *
 * @ingroup entity_crud
 * @see hook_entity_translation_delete()
 */
function hook_ENTITY_TYPE_translation_delete(\Drupal\Core\Entity\EntityInterface $translation) {
1219
  $variables = [
1220 1221
    '@language' => $translation->language()->getName(),
    '@label' => $translation->label(),
1222
  ];
1223 1224 1225
  \Drupal::logger('example')->notice('The @language translation of @label has just been deleted.', $variables);
}

1226
/**
1227 1228
 * Act before entity deletion.
 *
1229
 * @param \Drupal\Core\Entity\EntityInterface $entity
1230
 *   The entity object for the entity that is about to be deleted.
1231 1232 1233
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_predelete()
1234
 */
1235
function hook_entity_predelete(Drupal\Core\Entity\EntityInterface $entity) {
1236 1237
  // Count references to this entity in a custom table before they are removed
  // upon entity deletion.
1238
  $id = $entity->id();
1239
  $type = $entity->getEntityTypeId();
1240 1241 1242 1243 1244 1245 1246 1247
  $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.
1248
  db_merge('example_deleted_entity_statistics')
1249 1250
    ->key(['type' => $type, 'id' => $id])
    ->fields(['count' => $count])
1251
    ->execute();
1252 1253
}

1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
/**
 * Act before entity deletion of a particular entity type.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object for the entity that is about to be deleted.
 *
 * @ingroup entity_crud
 * @see hook_entity_predelete()
 */
function hook_ENTITY_TYPE_predelete(Drupal\Core\Entity\EntityInterface $entity) {
  // Count references to this entity in a custom table before they are removed
  // upon entity deletion.
  $id = $entity->id();
  $type = $entity->getEntityTypeId();
  $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.
  db_merge('example_deleted_entity_statistics')
1277 1278
    ->key(['type' => $type, 'id' => $id])
    ->fields(['count' => $count])
1279 1280 1281
    ->execute();
}

1282 1283 1284
/**
 * Respond to entity deletion.
 *
1285
 * This hook runs once the entity has been deleted from the storage.
1286
 *
1287
 * @param \Drupal\Core\Entity\EntityInterface $entity
1288
 *   The entity object for the entity that has been deleted.
1289 1290 1291
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_delete()
1292
 */
1293
function hook_entity_delete(Drupal\Core\Entity\EntityInterface $entity) {
1294 1295
  // Delete the entity's entry from a fictional table of all entities.
  db_delete('example_entity')
1296
    ->condition('type', $entity->getEntityTypeId())
1297
    ->condition('id', $entity->id())
1298 1299 1300
    ->execute();
}

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
/**
 * Respond to entity deletion of a particular type.
 *
 * This hook runs once the entity has been deleted from the storage.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object for the entity that has been deleted.
 *
 * @ingroup entity_crud
 * @see hook_entity_delete()
 */
function hook_ENTITY_TYPE_delete(Drupal\Core\Entity\EntityInterface $entity) {
  // Delete the entity's entry from a fictional table of all entities.
  db_delete('example_entity')
    ->condition('type', $entity->getEntityTypeId())
    ->condition('id', $entity->id())
    ->execute();
}

1320 1321 1322
/**
 * Respond to entity revision deletion.
 *
1323
 * This hook runs once the entity revision has been deleted from the storage.
1324
 *
1325
 * @param \Drupal\Core\Entity\EntityInterface $entity
1326
 *   The entity object for the entity revision that has been deleted.
1327 1328 1329
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_revision_delete()
1330 1331
 */
function hook_entity_revision_delete(Drupal\Core\Entity\EntityInterface $entity) {
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
  $referenced_files_by_field = _editor_get_file_uuids_by_field($entity);
  foreach ($referenced_files_by_field as $field => $uuids) {
    _editor_delete_file_usage($uuids, $entity, 1);
  }
}

/**
 * Respond to entity revision deletion of a particular type.
 *
 * This hook runs once the entity revision has been deleted from the storage.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object for the entity revision that has been deleted.
 *
 * @ingroup entity_crud
 * @see hook_entity_revision_delete()
 */
function hook_ENTITY_TYPE_revision_delete(Drupal\Core\Entity\EntityInterface $entity) {
  $referenced_files_by_field = _editor_get_file_uuids_by_field($entity);
  foreach ($referenced_files_by_field as $field => $uuids) {
    _editor_delete_file_usage($uuids, $entity, 1);
  }
1354 1355
}

1356 1357 1358
/**
 * Act on entities being assembled before rendering.
 *
1359
 * @param &$build
1360 1361
 *   A renderable array representing the entity content. The module may add
 *   elements to $build prior to rendering. The structure of $build is a
1362 1363
 *   renderable array as expected by
 *   \Drupal\Core\Render\RendererInterface::render().
1364
 * @param \Drupal\Core\Entity\EntityInterface $entity
1365
 *   The entity object.
1366
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
1367
 *   The entity view display holding the display options configured for the
1368
 *   entity components.
1369 1370 1371 1372
 * @param $view_mode
 *   The view mode the entity is rendered in.
 *
 * @see hook_entity_view_alter()
1373 1374 1375
 * @see hook_ENTITY_TYPE_view()
 *
 * @ingroup entity_crud
1376
 */
1377
function hook_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {