13

When developing a custom module, what is the correct way to set a module's weight?

markdorison
  • 139,374
  • 27
  • 55
  • 71

3 Answers3

25

This is the correct way to do it in Drupal 7

/**
 * Implements hook_enable()
 */
function YOUR_MODULE_enable() {
    db_update('system')
    ->fields(array('weight' => 1))
    ->condition('type', 'module')
    ->condition('name', 'YOUR_MODULE')
    ->execute();
}
jackocnr
  • 17,068
  • 10
  • 54
  • 63
20

The standard way is to do it in a query in the install hook.

From the devel module:

/**
 * Implementation of hook_install()
 */
function devel_install() {
  drupal_install_schema('devel');

  // New module weights in core: put devel as the very last in the chain.
  db_query("UPDATE {system} SET weight = 88 WHERE name = 'devel'");

  ...
}
googletorp
  • 33,075
  • 15
  • 67
  • 82
  • 1
    This looks correct but is the call to drupal_install_schema() required just to set the weight? – markdorison Jan 12 '11 at 17:55
  • 1
    You could also set the weight by hand... the drupal_install_schema() call is there because devel's install hook needs to install its schema. – David Eads Jan 12 '11 at 18:00
  • Take into consideration that setting the weight is not always all you need to do. In some cases I encountered, setting the "bootstrap" was required as well, and modules with lower weight but with "bootstrap" is loaded before "standard" modules - take that into account... – Shushu Jan 12 '11 at 19:31
  • See my answer for the Drupal 7 version. – jackocnr Oct 26 '12 at 09:40
4

if for some reason you have to stick it in an update hook, you will want to properly return the result from update_sql, lest you get nasty-looking innocuous errors.

function mymodule_update_6000(&$sandbox) {
  $res[] = update_sql("UPDATE {system} SET weight = 1 WHERE name = 'mymodule'");
  return $res;
}
Ryan Price
  • 41
  • 1