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

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

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

/**
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 * Add to entity type definitions.
 *
 * Modules may implement this hook to add information to defined entity types.
 *
 * @param array $entity_info
 *   An associative array of all entity type definitions, keyed by the entity
 *   type name. Passed by reference.
 *
 * @see \Drupal\Core\Entity\Entity
 * @see \Drupal\Core\Entity\EntityManager
 * @see entity_get_info()
 */
function hook_entity_info(&$entity_info) {
  // Add the 'Print' view mode for nodes.
  $entity_info['node']['view_modes']['print'] = array(
    'label' => t('Print'),
    'custom_settings' => FALSE,
  );
}

/**
 * Alter the entity type definitions.
36 37
 *
 * Modules may implement this hook to alter the information that defines an
38
 * entity type. All properties that are available in
39 40
 * \Drupal\Core\Entity\EntityManager can be altered here.
 *
41 42 43
 * Do not use this hook to add information to entity types. Use
 * hook_entity_info() for that instead.
 *
44 45
 * @param array $entity_info
 *   An associative array of all entity type definitions, keyed by the entity
46
 *   type name. Passed by reference.
47
 *
48 49 50
 * @see \Drupal\Core\Entity\Entity
 * @see \Drupal\Core\Entity\EntityManager
 * @see entity_get_info()
51 52 53
 */
function hook_entity_info_alter(&$entity_info) {
  // Set the controller class for nodes to an alternate implementation of the
54
  // Drupal\Core\Entity\EntityStorageControllerInterface interface.
55
  $entity_info['node']['controller_class'] = 'Drupal\mymodule\MyCustomNodeStorageController';
56 57 58 59 60 61 62 63
}

/**
 * Act on entities when loaded.
 *
 * This is a generic load hook called for all entity types loaded via the
 * entity API.
 *
64
 * @param array $entities
65
 *   The entities keyed by entity ID.
66
 * @param string $entity_type
67 68
 *   The type of entities being loaded (i.e. node, user, comment).
 */
69
function hook_entity_load($entities, $entity_type) {
70
  foreach ($entities as $entity) {
71
    $entity->foo = mymodule_add_something($entity);
72 73 74 75 76 77
  }
}

/**
 * Act on an entity before it is about to be created or updated.
 *
78
 * @param Drupal\Core\Entity\EntityInterface $entity
79 80
 *   The entity object.
 */
81
function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
82 83 84 85 86 87
  $entity->changed = REQUEST_TIME;
}

/**
 * Act on entities when inserted.
 *
88
 * @param Drupal\Core\Entity\EntityInterface $entity
89 90
 *   The entity object.
 */
91
function hook_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
92 93 94
  // Insert the new entity into a fictional table of all entities.
  db_insert('example_entity')
    ->fields(array(
95 96
      'type' => $entity->entityType(),
      'id' => $entity->id(),
97 98 99 100 101 102 103 104 105
      'created' => REQUEST_TIME,
      'updated' => REQUEST_TIME,
    ))
    ->execute();
}

/**
 * Act on entities when updated.
 *
106
 * @param Drupal\Core\Entity\EntityInterface $entity
107 108
 *   The entity object.
 */
109
function hook_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
110 111 112 113 114
  // Update the entity's entry in a fictional table of all entities.
  db_update('example_entity')
    ->fields(array(
      'updated' => REQUEST_TIME,
    ))
115 116
    ->condition('type', $entity->entityType())
    ->condition('id', $entity->id())
117 118 119 120
    ->execute();
}

/**
121 122 123
 * Act before entity deletion.
 *
 * This hook runs after the entity type-specific predelete hook.
124
 *
125
 * @param Drupal\Core\Entity\EntityInterface $entity
126 127
 *   The entity object for the entity that is about to be deleted.
 */
128
function hook_entity_predelete(Drupal\Core\Entity\EntityInterface $entity) {
129 130
  // Count references to this entity in a custom table before they are removed
  // upon entity deletion.
131 132
  $id = $entity->id();
  $type = $entity->entityType();
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
  $count = db_select('example_entity_data')
    ->condition('type', $type)
    ->condition('id', $id)
    ->countQuery()
    ->execute()
    ->fetchField();

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

/**
 * Respond to entity deletion.
 *
 * This hook runs after the entity type-specific delete hook.
 *
154
 * @param Drupal\Core\Entity\EntityInterface $entity
155
 *   The entity object for the entity that has been deleted.
156
 */
157
function hook_entity_delete(Drupal\Core\Entity\EntityInterface $entity) {
158 159
  // Delete the entity's entry from a fictional table of all entities.
  db_delete('example_entity')
160 161
    ->condition('type', $entity->entityType())
    ->condition('id', $entity->id())
162 163 164 165
    ->execute();
}

/**
166
 * Alter or execute an Drupal\Core\Entity\Query\EntityQueryInterface.
167
 *
168
 * @param \Drupal\Core\Entity\Query\QueryInterface $query
169 170 171 172 173 174 175
 *   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.
 */
176 177
function hook_entity_query_alter(\Drupal\Core\Entity\Query\QueryInterface $query) {
  // @todo: code example.
178 179 180 181 182
}

/**
 * Act on entities being assembled before rendering.
 *
183
 * @param Drupal\Core\Entity\EntityInterface $entity
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
 *   The entity object.
 * @param $view_mode
 *   The view mode the entity is rendered in.
 * @param $langcode
 *   The language code used for rendering.
 *
 * The module may add elements to $entity->content prior to rendering. The
 * structure of $entity->content is a renderable array as expected by
 * drupal_render().
 *
 * @see hook_entity_view_alter()
 * @see hook_comment_view()
 * @see hook_node_view()
 * @see hook_user_view()
 */
199
function hook_entity_view(Drupal\Core\Entity\EntityInterface $entity, $view_mode, $langcode) {
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
  $entity->content['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}

/**
 * Alter the results of ENTITY_view().
 *
 * This hook is called after the content has been assembled in a structured
 * array and may be used for doing processing which requires that the complete
 * entity content structure has been built.
 *
 * If a module wishes to act on the rendered HTML of the entity rather than the
 * structured content array, it may use this hook to add a #post_render
216 217
 * callback. Alternatively, it could also implement hook_preprocess_HOOK() for
 * the particular entity type template, if there is one (e.g., node.tpl.php).
218 219 220 221
 * See drupal_render() and theme() for details.
 *
 * @param $build
 *   A renderable array representing the entity content.
222
 * @param Drupal\Core\Entity\EntityInterface $entity
223
 *   The entity object being rendered.
224 225 226 227 228 229 230
 *
 * @see hook_entity_view()
 * @see hook_comment_view_alter()
 * @see hook_node_view_alter()
 * @see hook_taxonomy_term_view_alter()
 * @see hook_user_view_alter()
 */
231
function hook_entity_view_alter(&$build, Drupal\Core\Entity\EntityInterface $entity) {
232 233 234 235 236 237 238 239 240 241 242 243 244
  if ($build['#view_mode'] == 'full' && isset($build['an_additional_field'])) {
    // Change its weight.
    $build['an_additional_field']['#weight'] = -10;

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

/**
 * Act on entities as they are being prepared for view.
 *
 * Allows you to operate on multiple entities as they are being prepared for
245
 * view. Only use this if attaching the data during the entity loading phase
246 247
 * is not appropriate, for example when attaching other 'entity' style objects.
 *
248
 * @param array $entities
249
 *   The entities keyed by entity ID.
250 251
 * @param string $entity_type
 *   The type of entities being viewed (i.e. node, user, comment).
252
 */
253
function hook_entity_prepare_view($entities, $entity_type) {
254
  // Load a specific node into the user object for later theming.
255
  if (!empty($entities) && $entity_type == 'user') {
256 257 258 259 260 261
    $nodes = mymodule_get_user_nodes(array_keys($entities));
    foreach ($entities as $uid => $entity) {
      $entity->user_node = $nodes[$uid];
    }
  }
}
262 263 264 265 266 267

/**
 * 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.
268
 * @param Drupal\Core\Entity\EntityInterface $entity
269 270 271 272 273
 *   The entity that is being viewed.
 * @param array $context
 *   Array with additional context information, currently only contains the
 *   langcode the entity is viewed in.
 */
274
function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
275 276 277 278 279
  // For nodes, change the view mode when it is teaser.
  if ($entity->entityType() == 'node' && $view_mode == 'teaser') {
    $view_mode = 'my_custom_view_mode';
  }
}
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 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

/**
 * Define custom entity properties.
 *
 * @param string $entity_type
 *   The entity type for which to define entity properties.
 *
 * @return array
 *   An array of property information having the following optional entries:
 *   - definitions: An array of property definitions to add all entities of this
 *     type, keyed by property name. See
 *     Drupal\Core\TypedData\TypedDataManager::create() for a list of supported
 *     keys in property definitions.
 *   - optional: An array of property definitions for optional properties keyed
 *     by property name. Optional properties are properties that only exist for
 *     certain bundles of the entity type.
 *   - bundle map: An array keyed by bundle name containing the names of
 *     optional properties that entities of this bundle have.
 *
 * @see Drupal\Core\TypedData\TypedDataManager::create()
 * @see hook_entity_field_info_alter()
 * @see Drupal\Core\Entity\StorageControllerInterface::getPropertyDefinitions()
 */
function hook_entity_field_info($entity_type) {
  if (mymodule_uses_entity_type($entity_type)) {
    $info = array();
    $info['definitions']['mymodule_text'] = array(
      'type' => 'string_item',
      'list' => TRUE,
      'label' => t('The text'),
      'description' => t('A text property added by mymodule.'),
      'computed' => TRUE,
      'class' => '\Drupal\mymodule\EntityComputedText',
    );
    if ($entity_type == 'node') {
      // Add a property only to entities of the 'article' bundle.
      $info['optional']['mymodule_text_more'] = array(
        'type' => 'string_item',
        'list' => TRUE,
        'label' => t('More text'),
        'computed' => TRUE,
        'class' => '\Drupal\mymodule\EntityComputedMoreText',
      );
      $info['bundle map']['article'][0] = 'mymodule_text_more';
    }
    return $info;
  }
}

/**
 * Alter defined entity properties.
 *
 * @param array $info
 *   The property info array as returned by hook_entity_field_info().
 * @param string $entity_type
 *   The entity type for which entity properties are defined.
 *
 * @see hook_entity_field_info()
 */
function hook_entity_field_info_alter(&$info, $entity_type) {
  if (!empty($info['definitions']['mymodule_text'])) {
    // Alter the mymodule_text property to use a custom class.
    $info['definitions']['mymodule_text']['class'] = '\Drupal\anothermodule\EntityComputedText';
  }
}