Drupal 8: Creating Hook Alters programatically with Example

The Hook system will provide alter any content from one function from another in Drupal. The Drupal 8 Hook implementation are invoked with help of Core Drupal class function of moduleHandler(). This function will provide the object to execute all hook functions to alter the content.

The below is the syntax and example of implementing Hook alter in your modules.

Syntax: 

\Drupal::moduleHandler()->invokeAll('FUNCTION_NAME', array(ARGUMENT1, ARGUMENT2, ...));
 
/**
 * Implemented hook_FUNCTION_NAME().
 */
function hook_FUNCTION_NAME(ARGUMENT1, ARGUMENT2, ...) {
  // Perform alters for change.
}


Example: 

.....
.....
\Drupal::moduleHandler()->invokeAll('blog_content_view', array(&blog));
.....
.....
 
/**
 * Implemented hook_blog_content_view().
 */
function codeexpertz_blog_content_view(&blog) {
  $blog['title'] = 'Welcome to CodeExpertz';
}

 

Category: