How to disable and uninstall a Drupal module programmatically?
Asked Answered
R

4

20

I want to be able to disable and then uninstall a module programmatically on my local environment and then easily push that code to prod so everything gets updated.

I'm guessing it's something with the hook_update_N. But not sure where to start.

Reflexive answered 4/12, 2012 at 17:49 Comment(0)
R
47

Think I found the answer! Within the modules .install file, I added this code:

/**
 * Disable and uninstall the module.
 */
function MODULE_update_7200() {
  if( module_exists('MODULE')) {
    module_disable(array('MODULE'));
    drupal_uninstall_modules(array('MODULE'));
  }
}

The number in the function should reflect your drupal install. See how to number them here: http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_update_N/7

Reflexive answered 4/12, 2012 at 17:49 Comment(0)
A
11

Drupal 8

In Drupal 8 this is only one step now.

To be placed inside MYMODULE.install:

/**
 * Uninstall Field UI.
 */
function MYMODULE_update_8001(&$sandbox) {

  \Drupal::service('module_installer')->uninstall(['field_ui']);

}
Alike answered 10/10, 2017 at 11:51 Comment(1)
For anyone wondering, this also works in Drupal 9. Even when starting the update number with an 800X.Nakesha
E
1

In Drupal 8 you can use configuration API to enable and disable modules. For example, if you want to enable devel module. You have to add following code to the core.extension.yml devel: 0 If you want to uninstall you have to remove devel: 0 from the core.extension.yml

Examinant answered 3/5, 2018 at 7:4 Comment(2)
This is step 2. Step 1 would be to have it exported initially drush cex. Then your step. And then step 3: re-import the config drush cim. But actually that's not what OP is asking for. The question is: programmatically.Alike
In some circumstances it may not be possible to do a configuration import without first disabling a module in an update hook.Antisocial
I
1

you can use drush and forcefully uninstall the module just like the following:

drush eval "\$module_data = \Drupal::config('core.extension')->get('module'); unset(\$module_data['MODULE_NAME']); \Drupal::configFactory()->getEditable('core.extension')->set('module', \$module_data)->save();"
Illustrate answered 9/2, 2022 at 7:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.