Drupal: Programmatically installing and enabling modules in the .install file

| drupal

To make configuration management easier, we decided to make sure that all behavior-related changes are in the source code repository. So when I needed to add the reCAPTCHA module to the project, I needed to figure out how to programmatically install and enable the module with update code in another module’s .install file.

Here is some sample code to do so:

/**
 * Install and enable the captcha module.
 */
function yourmodule_update_1() {
  $ret = array();
  include_once('includes/install.inc');
  module_rebuild_cache();
  drupal_install_modules(array('recaptcha'));
  variable_set('recaptcha_public_key', 'PUBLIC KEY GOES HERE');
  variable_set('recaptcha_private_key', 'SECRET KEY GOES HERE');
  $ret[] = array(
    'success' => true,
    'query' => 'Installed recaptcha module and enabled it',
  );
  return $ret;
}
You can comment with Disqus or you can e-mail me at sacha@sachachua.com.