Skip to content

Core

hook_cron

/**
 * Perform periodic actions.
 *
 * Modules that require some commands to be executed periodically can
 * implement hook_cron(). The engine will then call the hook whenever a cron
 * run happens, as defined by the administrator. Typical tasks managed by
 * hook_cron() are database maintenance, backups, recalculation of settings
 * or parameters, automated mailing, and retrieving remote data.
 *
 * Short-running or non-resource-intensive tasks can be executed directly in
 * the hook_cron() implementation.
 *
 * Long-running tasks and tasks that could time out, such as retrieving remote
 * data, sending email, and intensive file tasks, should use the queue API
 * instead of executing the tasks directly. To do this, first define one or
 * more queues via a \Drupal\Core\Annotation\QueueWorker plugin. Then, add items
 * that need to be processed to the defined queues.
 *
 * @see queue
 */
function hook_cron() {
  // Short-running operation example, not using a queue:
  // Delete all expired records since the last cron run.
  $expires = \Drupal::state()->get('my_module.last_check', 0);
  $request_time = \Drupal::time()->getRequestTime();
  \Drupal::database()->delete('my_module_table')
    ->condition('expires', $expires, '>=')
    ->execute();
  \Drupal::state()->set('my_module.last_check', $request_time);

  // Long-running operation example, leveraging a queue:
  // Queue news feeds for updates once their refresh interval has elapsed.
  $queue = \Drupal::queue('my_module.feeds');
  $ids = \Drupal::entityTypeManager()->getStorage('my_module_feed')->getFeedIdsToRefresh();
  foreach (Feed::loadMultiple($ids) as $feed) {
    if ($queue->createItem($feed)) {
      // Add timestamp to avoid queueing item more than once.
      $feed->setQueuedTime($request_time);
      $feed->save();
    }
  }
  $ids = \Drupal::entityQuery('my_module_feed')
    ->accessCheck(FALSE)
    ->condition('queued', $request_time - (3600 * 6), '<')
    ->execute();
  if ($ids) {
    $feeds = Feed::loadMultiple($ids);
    foreach ($feeds as $feed) {
      $feed->setQueuedTime(0);
      $feed->save();
    }
  }
}

hook_data_type_info_alter

/**
 * Alter available data types for typed data wrappers.
 *
 * @param array $data_types
 *   An array of data type information.
 *
 * @see hook_data_type_info()
 */
function hook_data_type_info_alter(&$data_types) {
  $data_types['email']['class'] = '\Drupal\my_module\Type\Email';
}

hook_queue_info_alter

/**
 * Alter cron queue information before cron runs.
 *
 * Called by \Drupal\Core\Cron to allow modules to alter cron queue settings
 * before any jobs are processed.
 *
 * @param array $queues
 *   An array of cron queue information.
 *
 * @see \Drupal\Core\Queue\QueueWorkerInterface
 * @see \Drupal\Core\Annotation\QueueWorker
 * @see \Drupal\Core\Cron
 *
 */
function hook_queue_info_alter(&$queues) {
  // This site has many feeds so let's spend 90 seconds on each cron run
  // updating feeds instead of the default 60.
  $queues['my_module_feeds']['cron']['time'] = 90;
}

hook_condition_info_alter

/**
 * Alter the information provided in ConditionManager::getDefinitions().
 *
 * @param array $definitions
 *   The array of condition definitions.
 */
function hook_condition_info_alter(array &$definitions) {
  // Add custom or modify existing condition definitions.
  if (isset($definitions['node_type']) && $definitions['node_type']['class'] == 'Drupal\node\Plugin\Condition\NodeType') {
    // If the node_type's class is unaltered, use a custom implementation.
    $definitions['node_type']['class'] = 'Drupal\my_module\Plugin\Condition\NodeType';
  }
}

hook_mail_alter

/**
 * Alter an email message created with MailManagerInterface->mail().
 *
 * Hook hook_mail_alter() allows modification of email messages created and sent
 * with MailManagerInterface->mail(). Usage examples include adding and/or
 * changing message text, message fields, and message headers.
 *
 * Email messages sent using functions other than MailManagerInterface->mail()
 * will not invoke hook_mail_alter(). For example, a contributed module directly
 * calling the MailInterface->mail() or PHP mail() function will not invoke
 * this hook. All core modules use MailManagerInterface->mail() for messaging,
 * it is best practice but not mandatory in contributed modules.
 *
 * @param array $message
 *   An array containing the message data. Keys in this array include:
 *   - 'id':
 *     The MailManagerInterface->mail() id of the message. Look at module source
 *     code or MailManagerInterface->mail() for possible id values.
 *   - 'to':
 *     The address or addresses the message will be sent to. The
 *     formatting of this string must comply with RFC 2822.
 *   - 'from':
 *     The address the message will be marked as being from, which is
 *     either a custom address or the site-wide default email address.
 *   - 'subject':
 *     Subject of the email to be sent. This must not contain any newline
 *     characters, or the email may not be sent properly.
 *   - 'body':
 *     An array of strings or objects that implement
 *     \Drupal\Component\Render\MarkupInterface containing the message text. The
 *     message body is created by concatenating the individual array strings
 *     into a single text string using "\n\n" as a separator.
 *   - 'headers':
 *     Associative array containing mail headers, such as From, Sender,
 *     MIME-Version, Content-Type, etc.
 *   - 'params':
 *     An array of optional parameters supplied by the caller of
 *     MailManagerInterface->mail() that is used to build the message before
 *     hook_mail_alter() is invoked.
 *   - 'langcode':
 *     The langcode used to build the message before invoking hook_mail_alter().
 *   - 'send':
 *     Set to FALSE to abort sending this email message.
 *
 * @see \Drupal\Core\Mail\MailManagerInterface::mail()
 */
function hook_mail_alter(&$message) {
  if ($message['id'] == 'module_name_messagekey') {
    if (!example_notifications_optin($message['to'], $message['id'])) {
      // If the recipient has opted to not receive such messages, cancel
      // sending.
      $message['send'] = FALSE;
      return;
    }
    $message['body'][] = "--\nMail sent out from " . \Drupal::config('system.site')->get('name');
  }
}

hook_mail

/**
 * Prepares a message based on parameters.
 *
 * This hook is called from MailManagerInterface->mail(). Note that hook_mail(),
 * unlike hook_mail_alter(), is only called on the $module argument to
 * MailManagerInterface->mail(), not all modules.
 *
 * @param string $key
 *   An identifier of the mail.
 * @param array $message
 *   An array to be filled in. Elements in this array include:
 *   - id: An ID to identify the mail sent. Look at module source code or
 *     MailManagerInterface->mail() for possible id values.
 *   - to: The address or addresses the message will be sent to. The
 *     formatting of this string must comply with RFC 2822.
 *   - subject: Subject of the email to be sent. This must not contain any
 *     newline characters, or the mail may not be sent properly.
 *     MailManagerInterface->mail() sets this to an empty
 *     string when the hook is invoked.
 *   - body: An array of lines containing the message to be sent. Drupal will
 *     format the correct line endings for you. MailManagerInterface->mail()
 *     sets this to an empty array when the hook is invoked. The array may
 *     contain either strings or objects implementing
 *     \Drupal\Component\Render\MarkupInterface.
 *   - from: The address the message will be marked as being from, which is
 *     set by MailManagerInterface->mail() to either a custom address or the
 *     site-wide default email address when the hook is invoked.
 *   - headers: Associative array containing mail headers, such as From,
 *     Sender, MIME-Version, Content-Type, etc.
 *     MailManagerInterface->mail() pre-fills several headers in this array.
 * @param array $params
 *   An array of parameters supplied by the caller of
 *   MailManagerInterface->mail().
 *
 * @see \Drupal\Core\Mail\MailManagerInterface::mail()
 */
function hook_mail($key, &$message, $params): void {
  $account = $params['account'];
  $context = $params['context'];
  $variables = [
    '%site_name' => \Drupal::config('system.site')->get('name'),
    '%username' => $account->getDisplayName(),
  ];
  if ($context['hook'] == 'taxonomy') {
    $entity = $params['entity'];
    $vocabulary = Vocabulary::load($entity->id());
    $variables += [
      '%term_name' => $entity->name,
      '%term_description' => $entity->description,
      '%term_id' => $entity->id(),
      '%vocabulary_name' => $vocabulary->label(),
      '%vocabulary_description' => $vocabulary->getDescription(),
      '%vocabulary_id' => $vocabulary->id(),
    ];
  }

  // Node-based variable translation is only available if we have a node.
  if (isset($params['node'])) {
    /** @var \Drupal\node\NodeInterface $node */
    $node = $params['node'];
    $variables += [
      '%uid' => $node->getOwnerId(),
      '%url' => $node->toUrl('canonical', ['absolute' => TRUE])->toString(),
      '%node_type' => $node->getBundleEntity()->label(),
      '%title' => $node->getTitle(),
      '%teaser' => $node->teaser,
      '%body' => $node->body,
    ];
  }
  $subject = strtr($context['subject'], $variables);
  $body = strtr($context['message'], $variables);
  $message['subject'] .= str_replace(["\r", "\n"], '', $subject);
  $message['body'][] = MailFormatHelper::htmlToText($body);
}

hook_mail_backend_info_alter

/**
 * Alter the list of mail backend plugin definitions.
 *
 * @param array $info
 *   The mail backend plugin definitions to be altered.
 *
 * @see \Drupal\Core\Annotation\Mail
 * @see \Drupal\Core\Mail\MailManager
 */
function hook_mail_backend_info_alter(&$info) {
  unset($info['test_mail_collector']);
}

hook_countries_alter

/**
 * Alter the default country list.
 *
 * @param string[][] $countries
 *   The associative array of countries keyed by two-letter country code.
 *
 * @see \Drupal\Core\Locale\CountryManager::getList()
 */
function hook_countries_alter(&$countries) {
  // Elbonia is now independent, so add it to the country list.
  $countries['EB'] = 'Elbonia';
}

hook_display_variant_plugin_alter

/**
 * Alter display variant plugin definitions.
 *
 * @param array $definitions
 *   The array of display variant definitions, keyed by plugin ID.
 *
 * @see \Drupal\Core\Display\VariantManager
 * @see \Drupal\Core\Display\Attribute\DisplayVariant
 */
function hook_display_variant_plugin_alter(array &$definitions) {
  $definitions['full_page']['admin_label'] = t('Block layout');
}

hook_layout_alter

/**
 * Allow modules to alter layout plugin definitions.
 *
 * @param \Drupal\Core\Layout\LayoutDefinition[] $definitions
 *   The array of layout definitions, keyed by plugin ID.
 */
function hook_layout_alter(&$definitions) {
  // Remove a layout.
  unset($definitions['twocol']);
}

hook_cache_flush

/**
 * Flush all persistent and static caches.
 *
 * This hook asks your module to clear all of its static caches,
 * in order to ensure a clean environment for subsequently
 * invoked data rebuilds.
 *
 * Do NOT use this hook for rebuilding information. Only use it to flush custom
 * caches.
 *
 * Static caches using drupal_static() do not need to be reset manually.
 * However, all other static variables that do not use drupal_static() must be
 * manually reset.
 *
 * This hook is invoked by drupal_flush_all_caches(). It runs before module data
 * is updated and before hook_rebuild().
 *
 * @see drupal_flush_all_caches()
 * @see hook_rebuild()
 */
function hook_cache_flush(): void {
  if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
    _update_cache_clear();
  }
}

hook_rebuild

/**
 * Rebuild data based upon refreshed caches.
 *
 * This hook allows your module to rebuild its data based on the latest/current
 * module data. It runs after hook_cache_flush() and after all module data has
 * been updated.
 *
 * This hook is only invoked after the system has been completely cleared;
 * i.e., all previously cached data is known to be gone and every API in the
 * system is known to return current information, so your module can safely rely
 * on all available data to rebuild its own.
 *
 * @see hook_cache_flush()
 * @see drupal_flush_all_caches()
 */
function hook_rebuild(): void {
  $themes = \Drupal::service('theme_handler')->listInfo();
  foreach ($themes as $theme) {
    _block_rehash($theme->getName());
  }
}

hook_config_import_steps_alter

/**
 * Alter the configuration synchronization steps.
 *
 * @param array $sync_steps
 *   A one-dimensional array of \Drupal\Core\Config\ConfigImporter method names
 *   or callables that are invoked to complete the import, in the order that
 *   they will be processed. Each callable item defined in $sync_steps should
 *   either be a global function or a public static method. The callable should
 *   accept a $context array by reference. For example:
 *     function _additional_configuration_step(&$context) {
 *       // Do stuff.
 *       // If finished set $context['finished'] = 1.
 *     }
 *   For more information on creating batches, see the Batch operations
 *   documentation.
 *
 * @see callback_batch_operation()
 * @see \Drupal\Core\Config\ConfigImporter::initialize()
 */
function hook_config_import_steps_alter(&$sync_steps, \Drupal\Core\Config\ConfigImporter $config_importer) {
  $deletes = $config_importer->getUnprocessedConfiguration('delete');
  if (isset($deletes['field.storage.node.body'])) {
    $sync_steps[] = '_additional_configuration_step';
  }
}

hook_config_schema_info_alter

/**
 * Alter config typed data definitions.
 *
 * For example you can alter the typed data types representing each
 * configuration schema type to change default labels or form element renderers
 * used for configuration translation.
 *
 * If implementations of this hook add or remove configuration schema a
 * ConfigSchemaAlterException will be thrown. Keep in mind that there are tools
 * that may use the configuration schema for static analysis of configuration
 * files, like the string extractor for the localization system. Such systems
 * won't work with dynamically defined configuration schemas.
 *
 * For adding new data types use configuration schema YAML files instead.
 *
 * @param array $definitions
 *   Associative array of configuration type definitions keyed by schema type
 *   names. The elements are themselves array with information about the type.
 *
 * @see \Drupal\Core\Config\TypedConfigManager
 * @see \Drupal\Core\Config\Schema\ConfigSchemaAlterException
 */
function hook_config_schema_info_alter(&$definitions) {
  // Enhance the text and date type definitions with classes to generate proper
  // form elements in ConfigTranslationFormBase. Other translatable types will
  // appear as a one line textfield.
  $definitions['text']['form_element_class'] = '\Drupal\config_translation\FormElement\Textarea';
  $definitions['date_format']['form_element_class'] = '\Drupal\config_translation\FormElement\DateFormat';
}

hook_config_action_alter

/**
 * Alter config action plugin definitions.
 *
 * @param array[] $definitions
 *   The array of config action plugin definitions, keyed by plugin ID.
 *
 * @see \Drupal\Core\Config\Action\ConfigActionManager
 * @see \Drupal\Core\Config\Action\Attribute\ConfigAction
 */
function hook_config_action_alter(array &$definitions): void {
  // Create an alias for an existing config action.
  $definitions['editor:addItemsToToolbar'] = $definitions['editor:addItemToToolbar'];
}

hook_validation_constraint_alter

/**
 * Alter validation constraint plugin definitions.
 *
 * @param array[] $definitions
 *   The array of validation constraint definitions, keyed by plugin ID.
 *
 * @see \Drupal\Core\Validation\ConstraintManager
 * @see \Drupal\Core\Validation\Attribute\Constraint
 */
function hook_validation_constraint_alter(array &$definitions) {
  $definitions['Null']['class'] = '\Drupal\my_module\Plugin\Validation\Constraints\MyClass';
}