Warning message

Documentation is currently being migrated into the new system. Some pages might be temporarily missing, and some guides might appear empty. Thank you for your patience while we are improving Drupal.org documentation.

Basic file skeleton + CRUD hooks

Last updated on
October 14, 2016 - 21:22

Values to replace:

{ENTITY_ID} The internal identifier for your entity, e.g. "taxonomy_term".
{ENTITY} The term for a single entity.
{ENTITIES} The term for several entities.
{$ENTITY} A variable for a single entity.
{$ENTITIES} A variable for an array of entities.
{ENTITY_CLASS} The entity class for your entity.
/**
 * @file
 * Hooks provided by this module.
 */

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

/**
 * Acts on {ENTITIES} being loaded from the database.
 *
 * This hook is invoked during {ENTITY} loading, which is handled by
 * entity_load(), via the EntityCRUDController.
 *
 * @param array {$ENTITIES}
 *   An array of {ENTITY} entities being loaded, keyed by id.
 *
 * @see hook_entity_load()
 */
function hook_{ENTITY_ID}_load(array {$ENTITIES}) {
  $result = db_query('SELECT pid, foo FROM {mytable} WHERE pid IN(:ids)', array(':ids' => array_keys({$ENTITIES})));
  foreach ($result as $record) {
    {$ENTITIES}[$record->pid]->foo = $record->foo;
  }
}

/**
 * Responds when a {ENTITY} is inserted.
 *
 * This hook is invoked after the {ENTITY} is inserted into the database.
 *
 * @param {ENTITY_CLASS} {$ENTITY}
 *   The {ENTITY} that is being inserted.
 *
 * @see hook_entity_insert()
 */
function hook_{ENTITY_ID}_insert({ENTITY_CLASS} {$ENTITY}) {
  db_insert('mytable')
    ->fields(array(
      'id' => entity_id('{ENTITY_ID}', {$ENTITY}),
      'extra' => print_r({$ENTITY}, TRUE),
    ))
    ->execute();
}

/**
 * Acts on a {ENTITY} being inserted or updated.
 *
 * This hook is invoked before the {ENTITY} is saved to the database.
 *
 * @param {ENTITY_CLASS} {$ENTITY}
 *   The {ENTITY} that is being inserted or updated.
 *
 * @see hook_entity_presave()
 */
function hook_{ENTITY_ID}_presave({ENTITY_CLASS} {$ENTITY}) {
  {$ENTITY}->name = 'foo';
}

/**
 * Responds to a {ENTITY} being updated.
 *
 * This hook is invoked after the {ENTITY} has been updated in the database.
 *
 * @param {ENTITY_CLASS} {$ENTITY}
 *   The {ENTITY} that is being updated.
 *
 * @see hook_entity_update()
 */
function hook_{ENTITY_ID}_update({ENTITY_CLASS} {$ENTITY}) {
  db_update('mytable')
    ->fields(array('extra' => print_r({$ENTITY}, TRUE)))
    ->condition('id', entity_id('{ENTITY_ID}', {$ENTITY}))
    ->execute();
}

/**
 * Responds to {ENTITY} deletion.
 *
 * This hook is invoked after the {ENTITY} has been removed from the database.
 *
 * @param {ENTITY_CLASS} {$ENTITY}
 *   The {ENTITY} that is being deleted.
 *
 * @see hook_entity_delete()
 */
function hook_{ENTITY_ID}_delete({ENTITY_CLASS} {$ENTITY}) {
  db_delete('mytable')
    ->condition('pid', entity_id('{ENTITY_ID}', {$ENTITY}))
    ->execute();
}

/**
 * @}
 */