entity.api.php 72.7 KB
Newer Older
1 2 3 4 5 6 7
<?php

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

8
use Drupal\Component\Utility\String;
9
use Drupal\Core\Entity\ContentEntityInterface;
10
use Drupal\Core\Field\BaseFieldDefinition;
11
use Drupal\Core\Render\Element;
12

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
/**
 * @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:
 * \Drupal\Core\Entity\ContentEntityDatabaseStorage for content entities, and
 * \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.
 *
 * @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()
 *
 * 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.
 *
 * @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:
135
 * - Field configuration preSave(): hook_field_storage_config_update_forbid()
136 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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
 * - Node postSave(): hook_node_access_records() and
 *   hook_node_access_records_alter()
 * - Config entities that are acting as entity bundles, in postSave():
 *   hook_entity_bundle_create() or hook_entity_bundle_rename() as appropriate
 * - Comment: hook_comment_publish() and hook_comment_unpublish() as
 *   appropriate.
 *
 * @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)
 *
 * Some specific entity types have additional hooks that are run during
 * various steps in the process:
 * - Node entities: hook_node_validate() and hook_submit().
 *
 * @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.
 * $build = $view_builder->view($entity, 'view_mode_name', $language->id);
 * @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()
 * @}
 */

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 274 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
/**
 * @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;
 * for more detailed information, see https://drupal.org/developing/api/entity
 *
 * @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.
 * - Define an interface for your entity's get/set methods, extending either
 *   \Drupal\Core\Config\Entity\ConfigEntityInterface or
 *   \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.
 * - The 'id' annotation gives the entity type ID, and the 'label' annotation
 *   gives the human-readable name of the entity type. If you are defining a
 *   content entity type that uses bundles, the 'bundle_label' annotation gives
 *   the human-readable name to use for a bundle of this entity type (for
 *   example, "Content type" for the Node entity).
 * - The annotation will refer to several controller classes, which you will
 *   also need to define:
 *   - 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'
 *     annotation has value TRUE), define a class that extends
 *     \Drupal\content_translation\ContentTranslationHandler, to translate
 *     the content. Configuration translation is handled automatically by the
 *     Configuration Translation module, without the need of a controller class.
 *   - access: If your configuration entity has complex permissions, you might
302 303
 *     need an access control handling, implementing
 *     \Drupal\Core\Entity\EntityAccessControlHandlerInterface, but most entities
304
 *     can just use the 'admin_permission' annotation instead. Note that if you
305
 *     are creating your own access control handler, you should override the
306 307 308 309 310 311
 *     checkAccess() and checkCreateAccess() methods, not access().
 *   - storage: A class implementing
 *     \Drupal\Core\Entity\EntityStorageInterface. If not specified, content
 *     entities will use \Drupal\Core\Entity\ContentEntityDatabaseStorage, and
 *     config entities will use \Drupal\Core\Config\Entity\ConfigEntityStorage.
 *     You can extend one of these classes to provide custom behavior.
312 313
 *   - views_data: A class implementing \Drupal\views\EntityViewsDataInterface
 *     to provide views data for the entity type.
314 315 316 317 318 319 320 321 322 323
 * - 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
 *   \Drupal\Core\Entity\EntityType. Your module will also need to set up its
 *   database tables using hook_schema().
 * - 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;
324
 *   see the entity.node.canonical route in node.routing.yml for an example, and see
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
 *   @ref sec_routes below for some notes.
 * - Define routing and links for the various URLs associated with the entity.
 *   These go into the 'links' annotation, with the link type as the key, and
 *   the route machine name (defined in your module's routing.yml file) as the
 *   value; see @ref sec_routes below for some routing notes. Typical link
 *   types are:
 *   - 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.
 *   - admin-form: Form for editing bundle or entity type settings.
 *   - Other link types specific to your entity type can also be defined.
 * - 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'
 *   annotation) of this configuration entity class goes into the
 *   'bundle_entity_type' annotation 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 value for
 *   'bundle_entity_type' on the \Drupal\node\Entity\Node class. Also, the
 *   bundle config entity type annotation must have a 'bundle_of' entry,
 *   giving the machine name of the entity type it is acting as a bundle for.
 * - Additional annotations can be seen on entity class examples such as
 *   \Drupal\node\Entity\Node (content) and \Drupal\user\Entity\Role
 *   (configuration). These annotations are documented on
 *   \Drupal\Core\Entity\EntityType.
 *
 * @section sec_routes Entity routes
 * Entity routes, like other routes, are defined in *.routing.yml files; see
 * the @link menu Menu and routing @endlink topic for more information. Here
 * is a typical entry, for the block configure form:
 * @code
357
 * entity.block.edit_form:
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
 *   path: '/admin/structure/block/manage/{block}'
 *   defaults:
 *     _entity_form: 'block.default'
 *     _title: 'Configure block'
 *   requirements:
 *     _entity_access: 'block.update'
 * @endcode
 * Some notes:
 * - 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
 *   _content or _form. The value is composed of the entity type machine name
 *   and a form controller type from the entity annotation (see @ref define
 *   above more more on controllers and annotation). So, in this example,
 *   block.default refers to the 'default' form controller on the block entity
 *   type, whose annotation contains:
 *   @code
 *   controllers = {
 *     "form" = {
 *       "default" = "Drupal\block\BlockForm",
 *   @endcode
 *
 * @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'
 * annotation on the entity class), and note that you should use dependency
 * injection to retrieve this object if possible. See the
 * @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:
 * $query_service = $container->get('entity.query');
 * $query = $query_service->get('your_entity_type');
 * @endcode
 * If you need aggregation, there is an aggregate query avaialable, which
 * implements \Drupal\Core\Entity\Query\QueryAggregateInterface:
 * @code
 * $query \Drupal::entityQueryAggregate('your_entity_type');
 * // Or:
 * $query = $query_service->getAggregate('your_entity_type');
 * @endcode
 * Also, you should use dependency injection to get this object if
 * possible; the service you need is entity.query, and its methods getQuery()
 * or getAggregateQuery() will get the query object.
 *
 * 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
 * // You can omit the language ID if the default language is being used.
 * $build = $view_builder->view($entity, 'view_mode_name', $language->id);
 * // $build is a render array.
 * $rendered = drupal_render($build);
 * @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.
 *
483
 * The default entity access control handler invokes two hooks while checking
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
 * 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
 * @}
 */

501 502 503 504 505
/**
 * @addtogroup hooks
 * @{
 */

506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
/**
 * 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
 *    The account trying to access the entity.
 * @param string $langcode
 *    The code of the language $entity is accessed in.
 *
 * @return bool|null
 *   A boolean to explicitly allow or deny access, or NULL to neither allow nor
 *   deny access.
 *
522
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
523 524 525 526
 * @see hook_entity_create_access()
 * @see hook_ENTITY_TYPE_access()
 *
 * @ingroup entity_api
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
 */
function hook_entity_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account, $langcode) {
  return NULL;
}

/**
 * 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
 *    The account trying to access the entity.
 * @param string $langcode
 *    The code of the language $entity is accessed in.
 *
 * @return bool|null
 *   A boolean to explicitly allow or deny access, or NULL to neither allow nor
 *   deny access.
 *
548
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
549 550 551 552
 * @see hook_ENTITY_TYPE_create_access()
 * @see hook_entity_access()
 *
 * @ingroup entity_api
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
 */
function hook_ENTITY_TYPE_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account, $langcode) {
  return NULL;
}

/**
 * Control entity create access.
 *
 * @param \Drupal\Core\Session\AccountInterface $account
 *    The account trying to access the entity.
 * @param string $langcode
 *    The code of the language $entity is accessed in.
 *
 * @return bool|null
 *   A boolean to explicitly allow or deny access, or NULL to neither allow nor
 *   deny access.
 *
570
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
571 572 573 574
 * @see hook_entity_access()
 * @see hook_ENTITY_TYPE_create_access()
 *
 * @ingroup entity_api
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
 */
function hook_entity_create_access(\Drupal\Core\Session\AccountInterface $account, $langcode) {
  return NULL;
}

/**
 * Control entity create access for a specific entity type.
 *
 * @param \Drupal\Core\Session\AccountInterface $account
 *    The account trying to access the entity.
 * @param string $langcode
 *    The code of the language $entity is accessed in.
 *
 * @return bool|null
 *   A boolean to explicitly allow or deny access, or NULL to neither allow nor
 *   deny access.
 *
592
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
593 594 595 596
 * @see hook_ENTITY_TYPE_access()
 * @see hook_entity_create_access()
 *
 * @ingroup entity_api
597 598 599 600 601
 */
function hook_ENTITY_TYPE_create_access(\Drupal\Core\Session\AccountInterface $account, $langcode) {
  return NULL;
}

602
/**
603 604
 * Add to entity type definitions.
 *
605 606
 * Modules may implement this hook to add information to defined entity types,
 * as defined in \Drupal\Core\Entity\EntityTypeInterface.
607
 *
608
 * @param \Drupal\Core\Entity\EntityTypeInterface[] $entity_types
609 610 611 612
 *   An associative array of all entity type definitions, keyed by the entity
 *   type name. Passed by reference.
 *
 * @see \Drupal\Core\Entity\Entity
613
 * @see \Drupal\Core\Entity\EntityTypeInterface
614
 */
615 616
function hook_entity_type_build(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
617
  // Add a form for a custom node form without overriding the default
618
  // node form. To override the default node form, use hook_entity_type_alter().
619
  $entity_types['node']->setFormClass('mymodule_foo', 'Drupal\mymodule\NodeFooForm');
620 621
}

622 623 624 625 626 627 628 629 630
/**
 * 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.
 *
 * Do not use this hook to add information to entity types, unless you are just
631
 * filling-in default values. Use hook_entity_type_build() instead.
632
 *
633
 * @param \Drupal\Core\Entity\EntityTypeInterface[] $entity_types
634 635 636 637 638 639
 *   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
 */
640 641
function hook_entity_type_alter(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
642
  // Set the controller class for nodes to an alternate implementation of the
643 644
  // Drupal\Core\Entity\EntityStorageInterface interface.
  $entity_types['node']->setStorageClass('Drupal\mymodule\MyCustomNodeStorage');
645 646
}

647 648 649 650 651 652
/**
 * 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.
 *
653 654
 * @see \Drupal\Core\Entity\EntityManagerInterface::getAllViewModes()
 * @see \Drupal\Core\Entity\EntityManagerInterface::getViewModes()
655 656 657
 * @see hook_entity_view_mode_info()
 */
function hook_entity_view_mode_info_alter(&$view_modes) {
658
  $view_modes['user']['full']['status'] = TRUE;
659 660 661 662 663 664 665 666 667 668 669 670 671
}

/**
 * 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.
672 673
 *   - translatable: (optional) A boolean value specifying whether this bundle
 *     has translation support enabled. Defaults to FALSE.
674 675 676 677 678
 *
 * @see entity_get_bundles()
 * @see hook_entity_bundle_info_alter()
 */
function hook_entity_bundle_info() {
679
  $bundles['user']['user']['label'] = t('User');
680 681 682 683 684 685 686 687 688 689 690 691 692 693
  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');
694 695
}

696 697 698 699 700
/**
 * Act on entity_bundle_create().
 *
 * This hook is invoked after the operation has been performed.
 *
701
 * @param string $entity_type_id
702 703 704
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param string $bundle
 *   The name of the bundle.
705 706
 *
 * @see entity_crud
707
 */
708
function hook_entity_bundle_create($entity_type_id, $bundle) {
709 710
  // When a new bundle is created, the menu needs to be rebuilt to add the
  // Field UI menu item tabs.
711
  \Drupal::service('router.builder')->setRebuildNeeded();
712 713 714 715 716 717 718
}

/**
 * Act on entity_bundle_rename().
 *
 * This hook is invoked after the operation has been performed.
 *
719
 * @param string $entity_type_id
720 721 722 723 724
 *   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.
725 726
 *
 * @see entity_crud
727
 */
728
function hook_entity_bundle_rename($entity_type_id, $bundle_old, $bundle_new) {
729
  // Update the settings associated with the bundle in my_module.settings.
730
  $config = \Drupal::config('my_module.settings');
731
  $bundle_settings = $config->get('bundle_settings');
732 733 734
  if (isset($bundle_settings[$entity_type_id][$bundle_old])) {
    $bundle_settings[$entity_type_id][$bundle_new] = $bundle_settings[$entity_type_id][$bundle_old];
    unset($bundle_settings[$entity_type_id][$bundle_old]);
735 736 737 738 739 740 741 742 743
    $config->set('bundle_settings', $bundle_settings);
  }
}

/**
 * Act on entity_bundle_delete().
 *
 * This hook is invoked after the operation has been performed.
 *
744
 * @param string $entity_type_id
745 746 747
 *   The type of entity; for example, 'node' or 'user'.
 * @param string $bundle
 *   The bundle that was just deleted.
748 749
 *
 * @ingroup entity_crud
750
 */
751
function hook_entity_bundle_delete($entity_type_id, $bundle) {
752
  // Remove the settings associated with the bundle in my_module.settings.
753
  $config = \Drupal::config('my_module.settings');
754
  $bundle_settings = $config->get('bundle_settings');
755 756
  if (isset($bundle_settings[$entity_type_id][$bundle])) {
    unset($bundle_settings[$entity_type_id][$bundle]);
757 758 759 760
    $config->set('bundle_settings', $bundle_settings);
  }
}

761 762 763 764 765 766 767 768
/**
 * 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.
769 770 771
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_create()
772 773
 */
function hook_entity_create(\Drupal\Core\Entity\EntityInterface $entity) {
774
  if ($entity instanceof ContentEntityInterface && !$entity->foo->value) {
775 776 777 778
    $entity->foo->value = 'some_initial_value';
  }
}

779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
/**
 * Act on a newly created entity of a specific type.
 *
 * 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.
 *
 * @ingroup entity_crud
 * @see hook_entity_create()
 */
function hook_ENTITY_TYPE_create(\Drupal\Core\Entity\EntityInterface $entity) {
  if (!$entity->foo->value) {
    $entity->foo->value = 'some_initial_value';
  }
}

797 798 799 800 801 802
/**
 * Act on entities when loaded.
 *
 * This is a generic load hook called for all entity types loaded via the
 * entity API.
 *
803 804 805 806
 * hook_entity_storage_load() should be used to load additional data for
 * content entities.
 *
 * @param \Drupal\Core\Entity\EntityInterface[] $entities
807
 *   The entities keyed by entity ID.
808
 * @param string $entity_type_id
809
 *   The type of entities being loaded (i.e. node, user, comment).
810 811 812
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_load()
813
 */
814
function hook_entity_load(array $entities, $entity_type_id) {
815
  foreach ($entities as $entity) {
816
    $entity->foo = mymodule_add_something($entity);
817 818 819 820
  }
}

/**
821 822 823 824 825 826 827 828 829 830 831 832 833 834
 * 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);
  }
}

835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
/**
 * 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);
  }
}

869 870
/**
 * Act on an entity before it is created or updated.
871
 *
872
 * @param \Drupal\Core\Entity\EntityInterface $entity
873
 *   The entity object.
874 875 876
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_presave()
877
 */
878
function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
 if ($entity instanceof ContentEntityInterface && $entity->isTranslatable()) {
   $attributes = \Drupal::request()->attributes;
   \Drupal::service('content_translation.synchronizer')->synchronizeFields($entity, $entity->language()->id, $attributes->get('source_langcode'));
  }
}

/**
 * Act on a specific type of entity before it is created or updated.
 *
 * @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()) {
    $attributes = \Drupal::request()->attributes;
    \Drupal::service('content_translation.synchronizer')->synchronizeFields($entity, $entity->language()->id, $attributes->get('source_langcode'));
  }
899 900 901
}

/**
902 903 904 905
 * 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.
906
 *
907
 * @param \Drupal\Core\Entity\EntityInterface $entity
908
 *   The entity object.
909 910 911
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_insert()
912
 */
913
function hook_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
914 915 916
  // Insert the new entity into a fictional table of all entities.
  db_insert('example_entity')
    ->fields(array(
917
      'type' => $entity->getEntityTypeId(),
918
      'id' => $entity->id(),
919 920 921 922 923 924
      'created' => REQUEST_TIME,
      'updated' => REQUEST_TIME,
    ))
    ->execute();
}

925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
/**
 * 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')
    ->fields(array(
      'id' => $entity->id(),
      'created' => REQUEST_TIME,
      'updated' => REQUEST_TIME,
    ))
    ->execute();
}

948
/**
949 950 951 952
 * Respond to updates to an entity.
 *
 * This hook runs once the entity storage has been updated. Note that hook
 * implementations may not alter the stored entity data.
953
 *
954
 * @param \Drupal\Core\Entity\EntityInterface $entity
955
 *   The entity object.
956 957 958
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_update()
959
 */
960
function hook_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
961 962 963 964 965
  // Update the entity's entry in a fictional table of all entities.
  db_update('example_entity')
    ->fields(array(
      'updated' => REQUEST_TIME,
    ))
966
    ->condition('type', $entity->getEntityTypeId())
967
    ->condition('id', $entity->id())
968 969 970
    ->execute();
}

971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
/**
 * Respond to updates to an entity of a particular type.
 *
 * This hook runs once the entity storage has been updated. 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_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')
    ->fields(array(
      'updated' => REQUEST_TIME,
    ))
    ->condition('id', $entity->id())
    ->execute();
}

993
/**
994 995 996 997
 * 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.
998 999 1000
 *
 * @param \Drupal\Core\Entity\EntityInterface $translation
 *   The entity object of the translation just stored.
1001 1002 1003
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_translation_insert()
1004 1005 1006 1007 1008 1009
 */
function hook_entity_translation_insert(\Drupal\Core\Entity\EntityInterface $translation) {
  $variables = array(
    '@language' => $translation->language()->name,
    '@label' => $translation->getUntranslated()->label(),
  );
1010
  \Drupal::logger('example')->notice('The @language translation of @label has just been stored.', $variables);
1011 1012
}

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
/**
 * 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) {
  $variables = array(
    '@language' => $translation->language()->name,
    '@label' => $translation->getUntranslated()->label(),
  );
  \Drupal::logger('example')->notice('The @language translation of @label has just been stored.', $variables);
}

1033
/**
1034 1035 1036
 * Respond to entity translation deletion.
 *
 * This hook runs once the entity translation has been deleted from storage.
1037 1038 1039
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The original entity object.
1040 1041 1042
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_translation_delete()
1043 1044
 */
function hook_entity_translation_delete(\Drupal\Core\Entity\EntityInterface $translation) {
1045
  $languages = \Drupal::languageManager()->getLanguages();
1046 1047 1048 1049
  $variables = array(
    '@language' => $languages[$langcode]->name,
    '@label' => $entity->label(),
  );
1050
  \Drupal::logger('example')->notice('The @language translation of @label has just been deleted.', $variables);
1051 1052
}

1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
/**
 * Respond to entity translation deletion of a particular type.
 *
 * This hook runs once the entity translation has been deleted from storage.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The original entity object.
 *
 * @ingroup entity_crud
 * @see hook_entity_translation_delete()
 */
function hook_ENTITY_TYPE_translation_delete(\Drupal\Core\Entity\EntityInterface $translation) {
  $languages = \Drupal::languageManager()->getLanguages();
  $variables = array(
    '@language' => $languages[$langcode]->name,
    '@label' => $entity->label(),
  );
  \Drupal::logger('example')->notice('The @language translation of @label has just been deleted.', $variables);
}

1073
/**
1074 1075
 * Act before entity deletion.
 *
1076
 * @param \Drupal\Core\Entity\EntityInterface $entity
1077
 *   The entity object for the entity that is about to be deleted.
1078 1079 1080
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_predelete()
1081
 */
1082
function hook_entity_predelete(Drupal\Core\Entity\EntityInterface $entity) {
1083 1084
  // Count references to this entity in a custom table before they are removed
  // upon entity deletion.
1085
  $id = $entity->id();
1086
  $type = $entity->getEntityTypeId();
1087 1088 1089 1090 1091 1092 1093 1094
  $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.
1095 1096 1097 1098
  db_merge('example_deleted_entity_statistics')
    ->key(array('type' => $type, 'id' => $id))
    ->fields(array('count' => $count))
    ->execute();
1099 1100
}

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
/**
 * 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')
    ->key(array('type' => $type, 'id' => $id))
    ->fields(array('count' => $count))
    ->execute();
}

1129 1130 1131
/**
 * Respond to entity deletion.
 *
1132
 * This hook runs once the entity has been deleted from the storage.
1133
 *
1134
 * @param \Drupal\Core\Entity\EntityInterface $entity
1135
 *   The entity object for the entity that has been deleted.
1136 1137 1138
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_delete()
1139
 */
1140
function hook_entity_delete(Drupal\Core\Entity\EntityInterface $entity) {
1141 1142
  // Delete the entity's entry from a fictional table of all entities.
  db_delete('example_entity')
1143
    ->condition('type', $entity->getEntityTypeId())
1144
    ->condition('id', $entity->id())
1145 1146 1147
    ->execute();
}

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
/**
 * 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();
}

1167 1168 1169
/**
 * Respond to entity revision deletion.
 *
1170
 * This hook runs once the entity revision has been deleted from the storage.
1171
 *
1172
 * @param \Drupal\Core\Entity\EntityInterface $entity
1173
 *   The entity object for the entity revision that has been deleted.
1174 1175 1176
 *
 * @ingroup entity_crud
 * @see hook_ENTITY_TYPE_revision_delete()
1177 1178
 */
function hook_entity_revision_delete(Drupal\Core\Entity\EntityInterface $entity) {
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
  $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);
  }
1201 1202
}

1203
/**
1204
 * Alter or execute an Drupal\Core\Entity\Query\EntityQueryInterface.
1205
 *
1206
 * @param \Drupal\Core\Entity\Query\QueryInterface $query
1207 1208 1209 1210 1211 1212 1213
 *   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.
 */
1214 1215
function hook_entity_query_alter(\Drupal\Core\Entity\Query\QueryInterface $query) {
  // @todo: code example.
1216 1217 1218 1219 1220
}

/**
 * Act on entities being assembled before rendering.
 *
1221 1222
 * @param &$build
 *   A renderable array representing the entity content.
1223
 * @param \Drupal\Core\Entity\EntityInterface $entity
1224
 *   The entity object.
1225
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
1226
 *   The entity view display holding the display options configured for the
1227
 *   entity components.
1228 1229 1230 1231 1232
 * @param $view_mode
 *   The view mode the entity is rendered in.
 * @param $langcode
 *   The language code used for rendering.
 *
1233 1234
 * The module may add elements to $build prior to rendering. The
 * structure of $build is a renderable array as expected by
1235 1236 1237
 * drupal_render().
 *
 * @see hook_entity_view_alter()
1238 1239 1240
 * @see hook_ENTITY_TYPE_view()
 *
 * @ingroup entity_crud
1241
 */
1242
function hook_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode, $langcode) {
1243 1244
  // 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
1245
  // entity bundle in hook_entity_extra_field_info().
1246
  if ($display->getComponent('mymodule_addition')) {
1247
    $build['mymodule_addition'] = array(
1248 1249 1250 1251
      '#markup' => mymodule_addition($entity),
      '#theme' => 'mymodule_my_additional_field',
    );
  }
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 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
 * Act on entities of a particular type being assembled before rendering.
 *
 * @param &$build
 *   A renderable array representing the entity content.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
 *   The entity view display holding the display options configured for the
 *   entity components.
 * @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 $build prior to rendering. The
 * structure of $build is a renderable array as expected by
 * drupal_render().
 *
 * @see hook_ENTITY_TYPE_view_alter()
 * @see hook_entity_view()
 *
 * @ingroup entity_crud
 */
function hook_ENTITY_TYPE_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $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_entity_extra_field_info().
  if ($display->getComponent('mymodule_addition')) {
    $build['mymodule_addition'] = array(
      '#markup' => mymodule_addition($entity),
      '#theme' => 'mymodule_my_additional_field',
    );
  }
}

/**
 * Alter the results of the entity build array.
1292 1293 1294 1295 1296 1297 1298
 *
 * 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
1299
 * callback. Alternatively, it could also implement hook_preprocess_HOOK() for
1300
 * the particular entity type template, if there is one (e.g., node.html.twig).
1301
 * See drupal_render() and _theme() for details.
1302
 *
1303
 * @param array &$build
1304
 *   A renderable array representing the entity content.
1305
 * @param \Drupal\Core\Entity\EntityInterface $entity
1306
 *   The entity object being rendered.
1307
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
1308
 *   The entity view display holding the display options configured for the
1309
 *   entity components.
1310 1311
 *
 * @see hook_entity_view()
1312 1313 1314
 * @see hook_ENTITY_TYPE_view_alter()
 *
 * @ingroup entity_crud
1315
 */
1316
function hook_entity_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
1317 1318 1319 1320 1321 1322 1323 1324 1325
  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';
  }
}

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
/**
 * Alter the results of the entity build array for a particular entity type.
 *
 * 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
 * callback. Alternatively, it could also implement hook_preprocess_HOOK() for
 * the particular entity type template, if there is one (e.g., node.html.twig).
 * See drupal_render() and _theme() for details.
 *
 * @param array &$build
 *   A renderable array representing the entity content.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object being rendered.
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
 *   The entity view display holding the display options configured for the
 *   entity components.
 *
 * @see hook_ENTITY_TYPE_view()
 * @see hook_entity_view_alter()
 *
 * @ingroup entity_crud
 */
function hook_ENTITY_TYPE_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  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';
  }
}

1362 1363 1364 1365
/**
 * Act on entities as they are being prepared for view.
 *
 * Allows you to operate on multiple entities as they are being prepared for
1366
 * view. Only use this if attaching the data during the entity loading phase
1367 1368
 * is not appropriate, for example when attaching other 'entity' style objects.
 *
1369
 * @param string $entity_type_id
1370
 *   The type of entities being viewed (i.e. node, user, comment).
1371 1372
 * @param array $entities
 *   The entities keyed by entity ID.
1373
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface[] $displays
1374
 *   The array of entity view displays holding the display options configured
1375 1376 1377
 *   for the entity components, keyed by bundle name.
 * @param string $view_mode
 *   The view mode.
1378 1379
 *
 * @ingroup entity_crud
1380
 */
1381
function hook_entity_prepare_view($entity_type_id, array $entities, array $displays, $view_mode) {
1382
  // Load a specific node into the user object for later theming.
1383
  if (!empty($entities) && $entity_type_id == 'user') {
1384 1385
    // Only do the extra work if the component is configured to be
    // displayed. This assumes a 'mymodule_addition' extra field has been
1386
    // defined for the entity bundle in hook_entity_extra_field_info().
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    $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];
      }
1398 1399 1400
    }
  }
}
1401 1402 1403 1404 1405 1406

/**
 * 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.
1407
 * @param \Drupal\Core\Entity\EntityInterface $entity
1408 1409 1410 1411
 *   The entity that is being viewed.
 * @param array $context
 *   Array with additional context information, currently only contains the
 *   langcode the entity is viewed in.
1412 1413
 *
 * @ingroup entity_crud
1414
 */
1415
function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
1416
  // For nodes, change the view mode when it is teaser.
1417
  if ($entity->getEntityTypeId() == 'node' && $view_mode == 'teaser') {
1418 1419 1420
    $view_mode = 'my_custom_view_mode';
  }
}
1421

1422
/**
1423
 * Alter entity renderable values before cache checking in drupal_render().
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
 *
 * Invoked for a specific entity type.
 *
 * The values in the #cache key of the renderable array are used to determine if
 * a cache entry exists for the entity's rendered output. Ideally only values
 * that pertain to caching should be altered in this hook.
 *
 * @param array &$build
 *   A renderable array containing the entity's caching and view mode values.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity that is being viewed.
 * @param string $view_mode
 *   The view_mode that is to be used to display the entity.
 * @param string $langcode
 *   The code of the language $entity is accessed in.
 *
 * @see drupal_render()
 * @see \Drupal\Core\Entity\EntityViewBuilder
1442 1443 1444
 * @see hook_entity_build_defaults_alter()
 *
 * @ingroup entity_crud
1445 1446 1447 1448 1449 1450
 */
function hook_ENTITY_TYPE_build_defaults_alter(array &$build, \Drupal\Core\Entity\EntityInterface $entity, $view_mode, $langcode) {

}

/**
1451
 * Alter entity renderable values before cache checking in drupal_render().
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
 *
 * The values in the #cache key of the renderable array are used to determine if
 * a cache entry exists for the entity's rendered output. Ideally only values
 * that pertain to caching should be altered in this hook.
 *
 * @param array &$build
 *   A renderable array containing the entity's caching and view mode values.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity that is being viewed.
 * @param string $view_mode
 *   The view_mode that is to be used to display the entity.
 * @param string $langcode
 *   The code of the language $entity is accessed in.
 *
 * @see drupal_render()
 * @see \Drupal\Core\Entity\EntityViewBuilder
1468 1469 1470
 * @see hook_ENTITY_TYPE_build_defaults_alter()
 *
 * @ingroup entity_crud
1471 1472 1473 1474 1475
 */
function hook_entity_build_defaults_alter(array &$build, \Drupal\Core\Entity\EntityInterface $entity, $view_mode, $langcode) {

}

1476
/**
1477
 * Alter the settings used for displaying an entity.
1478
 *
1479
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
1480
 *   The entity view display that will be used to display the entity
1481 1482 1483 1484 1485 1486
 *   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'...
1487 1488
 *
 * @ingroup entity_crud
1489
 */
1490
function hook_entity_view_display_alter(\Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, array $context) {
1491 1492
  // Leave field labels out of the search index.
  if ($context['entity_type'] == 'node' && $context['view_mode'] == 'search_index') {
1493 1494 1495 1496
    foreach ($display->getComponents() as $name => $options) {
      if (isset($options['label'])) {
        $options['label'] = 'hidden';
        $display->setComponent($name, $options);
1497 1498 1499 1500 1501
      }
    }
  }
}

1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
/**
 * Alter the render array generated by an EntityDisplay for an entity.
 *
 * @param array $build
 *   The renderable array generated by the EntityDisplay.
 * @param array $context
 *   An associative array containing:
 *   - entity: The entity being rendered.
 *   - view_mode: The view mode; for example, 'full' or 'teaser'.
 *   - display: The EntityDisplay holding the display options.
1512 1513
 *
 * @ingroup entity_crud
1514 1515 1516
 */
function hook_entity_display_build_alter(&$build, $context) {
  // Append RDF term mappings on displayed taxonomy links.
1517
  foreach (Element::children($build) as $field_name) {
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    $element = &$build[$field_name];
    if ($element['#field_type'] == 'entity_reference' && $element['#formatter'] == 'entity_reference_label') {
      foreach ($element['#items'] as $delta => $item) {
        $term = $item->entity;
        if (!empty($term->rdf_mapping['rdftype'])) {
          $element[$delta]['#options']['attributes']['typeof'] = $term->rdf_mapping['rdftype'];
        }
        if (!empty($term->rdf_mapping['name']['predicates'])) {
          $element[$delta]['#options']['attributes']['property'] = $term->rdf_mapping['name']['predicates'];
        }
      }
    }
  }
}

1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
/**
 * Acts on an entity object about to be shown on an entity form.
 *
 * This can be typically used to pre-fill entity values or change the form state
 * before the entity form is built. It is invoked just once when first building
 * the entity form. Rebuilds will not trigger a new invocation.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity that is about to be shown on the form.
 * @param $operation
 *   The current operation.
1544 1545
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The current state of the form.
1546
 *
1547
 * @see \Drupal\Core\Entity\EntityForm::prepareEntity()
1548 1549 1550
 * @see hook_ENTITY_TYPE_prepare_form()
 *
 * @ingroup entity_crud
1551
 */
1552
function hook_entity_prepare_form(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Form\FormStateInterface $form_state) {
1553 1554 1555 1556 1557 1558
  if ($operation == 'edit') {
    $entity->label->value = 'Altered label';
    $form_state['mymodule']['label_altered'] = TRUE;
  }
}

1559
/**
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
 * Acts on a particular type of entity object about to be in an entity form.
 *
 * This can be typically used to pre-fill entity values or change the form state
 * before the entity form is built. It is invoked just once when first building
 * the entity form. Rebuilds will not trigger a new invocation.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity that is about to be shown on the form.
 * @param $operation
 *   The current operation.
1570 1571
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The current state of the form.
1572 1573 1574 1575 1576 1577
 *
 * @see \Drupal\Core\Entity\EntityForm::prepareEntity()
 * @see hook_entity_prepare_form()
 *
 * @ingroup entity_crud
 */
1578
function hook_ENTITY_TYPE_prepare_form(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Form\FormStateInterface $form_state) {
1579 1580 1581 1582 1583 1584 1585 1586
  if ($operation == 'edit') {
    $entity->label->value = 'Altered label';
    $form_state['mymodule']['label_altered'] = TRUE;
  }
}

/**
 * Alter the settings used for displaying an entity form.
1587
 *
1588
 * @param \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display
1589 1590 1591 1592 1593 1594 1595
 *   The entity_form_display object that will be used to display the entity form
 *   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'.
 *   - form_mode: The form mode, e.g. 'default', 'profile', 'register'...
1596 1597
 *
 * @ingroup entity_crud
1598
 */
1599
function hook_entity_form_display_alter(\Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display, array $context) {
1600 1601 1602 1603 1604 1605 1606 1607
  // Hide the 'user_picture' field from the register form.
  if ($context['entity_type'] == 'user' && $context['form_mode'] == 'register') {
    $form_display->setComponent('user_picture', array(
      'type' => 'hidden',
    ));
  }
}

1608
/**
1609
 * Provides custom base field definitions for a content entity type.
1610
 *
1611 1612
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
1613
 *
1614 1615 1616 1617 1618 1619
 * @return \Drupal\Core\Field\FieldDefinitionInterface[]
 *   An array of field definitions, keyed by field name.
 *
 * @see hook_entity_base_field_info_alter()
 * @see hook_entity_bundle_field_info()
 * @see hook_entity_bundle_field_info_alter()
1620
 * @see \Drupal\Core\Field\FieldDefinitionInterface
1621
 * @see \Drupal\Core\Entity\EntityManagerInterface::getFieldDefinitions()
1622
 */
1623 1624 1625
function hook_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'node') {
    $fields = array();
1626
    $fields['mymodule_text'] = BaseFieldDefinition::create('string')
1627 1628 1629 1630 1631
      ->setLabel(t('The text'))
      ->setDescription(t('A text property added by mymodule.'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\mymodule\EntityComputedText');

1632 1633 1634 1635 1636
    return $fields;
  }
}

/**
1637
 * Alter base field definitions for a content entity type.
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
 *
 * @param \Drupal\Core\Field\FieldDefinitionInterface[] $fields
 *   The array of base field definitions for the entity type.
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 *
 * @see hook_entity_base_field_info()
 * @see hook_entity_bundle_field_info()
 * @see hook_entity_bundle_field_info_alter()
 */
function hook_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  // Alter the mymodule_text field to use a custom class.
  if ($entity_type->id() == 'node' && !empty($fields['mymodule_text'])) {
    $fields['mymodule_text']->setClass('\Drupal\anothermodule\EntityComputedText');
  }
}

/**
 * Provides field definitions for a specific bundle within an entity type.
 *
1658 1659 1660 1661
 * Bundle fields either have to override an existing base field, or need to
 * provide a field storage definition via hook_entity_field_storage_info()
 * unless they are computed.
 *
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 * @param string $bundle
 *   The bundle.
 * @param \Drupal\Core\Field\FieldDefinitionInterface[] $base_field_definitions
 *   The list of base field definitions for the entity type.
 *
 * @return \Drupal\Core\Field\FieldDefinitionInterface[]
 *   An array of bundle field definitions, keyed by field name.
 *
 * @see hook_entity_base_field_info()
 * @see hook_entity_base_field_info_alter()
1674 1675
 * @see hook_entity_field_storage_info()
 * @see hook_entity_field_storage_info_alter()
1676 1677 1678 1679 1680 1681 1682 1683
 * @see hook_entity_bundle_field_info_alter()
 * @see \Drupal\Core\Field\FieldDefinitionInterface
 * @see \Drupal\Core\Entity\EntityManagerInterface::getFieldDefinitions()
 */
function hook_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
  // Add a property only to nodes of the 'article' bundle.
  if ($entity_type->id() == 'node' && $bundle == 'article') {
    $fields = array();
1684
    $fields['mymodule_text_more'] = BaseFieldDefinition::create('string')
1685 1686 1687
        ->setLabel(t('More text'))
        ->setComputed(TRUE)
        ->setClass('\Drupal\mymodule\EntityComputedMoreText');
1688
    return $fields;
1689 1690 1691 1692
  }
}

/**
1693
 * Alter bundle field definitions.
1694
 *
1695 1696 1697 1698 1699 1700
 * @param \Drupal\Core\Field\FieldDefinitionInterface[] $fields
 *   The array of bundle field definitions.
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 * @param string $bundle
 *   The bundle.
1701
 *
1702 1703 1704
 * @see hook_entity_base_field_info()
 * @see hook_entity_base_field_info_alter()
 * @see hook_entity_bundle_field_info()
1705
 */
1706 1707
function hook_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'node' && $bundle == 'article' && !empty($fields['mymodule_text'])) {
1708
    // Alter the mymodule_text field to use a custom class.
1709
    $fields['mymodule_text']->setClass('\Drupal\anothermodule\EntityComputedText');
1710 1711
  }
}
1712

1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
/**
 * Provides field storage definitions for a content entity type.
 *
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 *
 * @return \Drupal\Core\Field\FieldStorageDefinitionInterface[]
 *   An array of field storage definitions, keyed by field name.
 *
 * @see hook_entity_field_storage_info_alter()
 * @see \Drupal\Core\Field\FieldStorageDefinitionInterface
 * @see \Drupal\Core\Entity\EntityManagerInterface::getFieldStorageDefinitions()
 */
function hook_entity_field_storage_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  // Expose storage definitions for all exposed bundle fields.
  if ($entity_type->isFieldable()) {
    // Query by filtering on the ID as this is more efficient than filtering
    // on the entity_type property directly.
1731
    $ids = \Drupal::entityQuery('field_storage_config')
1732 1733 1734 1735
      ->condition('id', $entity_type->id() . '.', 'STARTS_WITH')
      ->execute();

    // Fetch all fields and key them by field name.
1736
    $field_storages = entity_load_multiple('field_storage_config', $ids);
1737
    $result = array();
1738 1739
    foreach ($field_storages as $field_storage) {
      $result[$field_storage->getName()] = $field_storage;
1740 1741 1742 1743 1744 1745
    }
    return $result;
  }
}

/**
1746
 * Alter field storage definitions for a content entity type.
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
 *
 * @param \Drupal\Core\Field\FieldStorageDefinitionInterface[] $fields
 *   The array of field storage definitions for the entity type.
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 *
 * @see hook_entity_field_storage_info()
 */
function hook_entity_field_storage_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  // Alter the max_length setting.
  if ($entity_type->id() == 'node' && !empty($fields['mymodule_text'])) {
    $fields['mymodule_text']->setSetting('max_length', 128);
  }
}

1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
/**
 * Declares entity operations.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity on which the linked operations will be performed.
 *
 * @return array
 *   An operations array as returned by
 *   \Drupal\Core\Entity\EntityListBuilderInterface::getOperations().
 */
function hook_entity_operation(\Drupal\Core\Entity\EntityInterface $entity) {
  $operations = array();
  $operations['translate'] = array(
    'title' => t('Translate'),
    'route_name' => 'foo_module.entity.translate',
    'weight' => 50,
  );

  return $operations;
}

1783 1784 1785 1786 1787
/**
 * Alter entity operations.
 *
 * @param array $operations
 *   Operations array as returned by
1788
 *   \Drupal\Core\Entity\EntityListBuilderInterface::getOperations().
1789 1790 1791 1792
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity on which the linked operations will be performed.
 */
function hook_entity_operation_alter(array &$operations, \Drupal\Core\Entity\EntityInterface $entity) {
1793 1794 1795 1796 1797
  // Alter the title and weight.
  $operations['translate']['title'] = t('Translate @entity_type', array(
    '@entity_type' => $entity->getEntityTypeId(),
  ));
  $operations['translate']['weight'] = 99;
1798 1799
}

1800 1801 1802
/**
 * Control access to fields.
 *
1803
 * This hook is invoked from
1804
 * \Drupal\Core\Entity\EntityAccessControlHandler::fieldAccess() to let modules
1805
 * grant or deny operations on fields.
1806 1807 1808
 *
 * @param string $operation
 *   The operation to be performed. See
1809
 *   \Drupal\Core\Access\AccessibleInterface::access() for possible values.
1810
 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
1811
 *   The field definition.
1812
 * @param \Drupal\Core\Session\AccountInterface $account
1813
 *   The user account to check.
1814
 * @param \Drupal\Core\Field\FieldItemListInterface $items
1815 1816
 *   (optional) The entity field object on which the operation is to be
 *   performed.
1817
 *
1818
 * @return bool|null
1819 1820 1821
 *   TRUE if access should be allowed, FALSE if access should be denied and NULL
 *   if the implementation has no opinion.
 */
1822
function hook_entity_field_access($operation, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, \Drupal\Core\Session\AccountInterface $account, \Drupal\Core\Field\FieldItemListInterface $items = NULL) {
1823
  if ($field_definition->getName() == 'field_of_interest' && $operation == 'edit') {
1824
    return $account->hasPermission('update field of interest');
1825 1826 1827 1828
  }
}

/**
1829
 * Alter the default access behavior for a given field.
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
 *
 * 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).
1841
 *   - field_definition: The field definition object
1842
 *     (\Drupal\Core\Field\FieldDefinitionInterface)
1843
 *   - account: The user account to check access for
1844
 *     (Drupal\user\Entity\User).
1845
 *   - items: (optional) The entity field items
1846
 *     (\Drupal\Core\Field\FieldItemListInterface).
1847 1848
 */
function hook_entity_field_access_alter(array &$grants, array $context) {
1849
  /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
1850
  $field_definition = $context['field_definition'];
1851
  if ($field_definition->getName() == 'field_of_interest' && $grants['node'] === FALSE) {
1852 1853 1854 1855 1856 1857 1858 1859
    // 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;
  }
}
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927

/**
 * Exposes "pseudo-field" components on content entities.
 *
 * Field UI's "Manage fields" and "Manage display" pages let users re-order
 * fields, but also non-field components. For nodes, these include elements
 * exposed by