When you add new modules to your project, you may be used to enabling them in the modules page (admin/modules). This does mean that you need to remember to enable these modules on the live site (and any other site in your pipeline).

Like most things in Drupal, you can automate the enabling of modules by doing it programmatically. This means that when you deploy your new modules to the new site, you won’t need to manually enable them. This saves time and reduces the chance that you accidentally forget which modules to enable.

Enable in an install file

The most common method, and the one I use, is to enable modules in an install file.

You can use a single function called module_enable() to do this. This function takes an array of modules that you want to enable.

module_enable(array('module_1', 'module_2', module_3));

By default, dependencies of the modules being enabled will also be enabled. But if you decide that you don’t want to enable dependencies, add FALSE as a second argument.

module_enable(array('module_1', 'module_2', module_3), FALSE);

Put this code in an update_N function in an install function. It is common to use a central deployment module to handle this. When you run update.php or drush updb, the module(s) will be enabled.

Here is a real world example of module_enable in a update_N function.

function site_deploy_update_7001() {
  module_enable(array('entity_view_mode', 'maxlength'));

Disable a module

If you want to disable a module, there is a conveniently named sister function called module_disable().

module_disable(array('module_1', 'module_2', module_3));

Dependencies will be automatically be disabled. Because this will result in a non-trivial performance hit, you can set this to FALSE if you know that you want to keep any dependent modules enabled.

module_disable(array('module_1', 'module_2', 'module_3')), FALSE);

Uninstall a module

You’d normally want to uninstall a module after disabling it and you need to call a second function for that, drupal_uninstall_modules().

module_disable(array('module_1', 'module_2', 'module_3'));
drupal_uninstall_modules(array('module_1', 'module_2', 'module_3'));

Let’s take a look at another real world example in a custom deployment module. This will disable and uninstall the same modules that were enabled in the previous example.

function site_deploy_update_7002() {
  module_disable(array('entity_view_mode', 'maxlength'));
  drupal_uninstall_modules(array('entity_view_mode', 'maxlength'));

Further reading

Programmatically enabling and disabling modules is a good example of automating updates. If you want to learn more about setting up a development module, check out Automate Drupal site updates with a deployment module.