Aug 2, 2014

hook_init() is gone, R.I.P. and drupal_add_js() deprecated

In Drupal 8 hook_init() has been removed. Generally speaking, it's described as being replaced by the Symfony components that provide access to events and to listening for them.

In our case, however, we have the relatively simple need of adding to certain pages the externally provided javascript code snippets that drive the use of the Optimizely service.

Given this need, I was able to use the existing hook_page_build() function instead of hook_init().

Drupal 7's drupal_add_js() has been removed. Actually, it has been renamed to _drupal_add_js() but it is strongly deprecated in favor of using the #attach key in render arrays.


Here's the relevant D7 code.

function optimizely_init() {
 
  $current_path = current_path();

  // Determine whether to process the current page, etc.
  // Other processing, setup, etc.

  $snippet_url = 'http://cdn.optimizely.com/js/' .
                  $project['project_code'] . '.js';

  drupal_add_js($snippet_url, 'external');
}



And the corresponding D8 code.

function optimizely_page_build(&$page) {

  $current_path = current_path();

  // Determine whether to process the current page, etc.
  // Other processing, etc.

  $snippet_url = 'http://cdn.optimizely.com/js/' .
                  $project['project_code'] . '.js';
                 
  $page['#attached']['js'][] = array(
                                  'type' => 'external',
                                  'data' => $snippet_url,
                                );

} 


Update: see  http://optimizely-to-drupal-8.blogspot.com/2015/01/beta-4-hookpagebuild-has-been-removed.html  for several changes applicable to this code.


Sources:

hook_init() removed
https://drupal.org/node/2013014

function hook_page_build
https://api.drupal.org/api/drupal/core!modules!system!system.api.php/function/hook_page_build/8

function _drupal_add_js
https://api.drupal.org/api/drupal/core!includes!common.inc/function/_drupal_add_js/8

1 comment:

  1. The king is dead, long live the king!

    Footnote:
    http://en.wikipedia.org/wiki/The_king_is_dead,_long_live_the_king!

    ReplyDelete