hook_uninstall not running? Drupal schoolboy errors #1

Tue, 28/03/2017 - 17:04 -- James Oakley
(Uninstall) Hook\
Image Credit: Raul Lieberwirth

I'll put this here, in case it helps anyone else.

I'm owning up to Drupal Schoolboy Error #1.

I was writing a very simple module. It did so little, that I wanted to keep things as simple as possible — just a .info file, and a .module file.

I then included a couple of variables that could be set through the admin interface. Very simple modules rarely stay as simple as they begin, but I still thought I'd try to keep things in just those two files. Even though this was only for my own use, I wanted to design the module correctly. I didn't want to introduce technical debt, even if I would be the only debtor. So I wrote an implementation of hook_uninstall() to remove those variables when the module is uninstalled.

But the hook implementation wouldn't fire. My variables weren't being removed. So I put some calls to watchdog() in the hook implementation function, and nothing was appearing in the log. The hook_uninstall() code wasn't running.

I tried all the obvious things. First, I checked my spelling on the function name. That's caught me out before. Most recently, where my module had a 'd' in its name, but the function name had a 'b' in the corresponding place. But that wasn't it.

So I googled reasons why a hook may not fire correctly, but found nothing relevant.

Then I went back to the documentation. There are other cautionary comments in the docs for hook_uninstall, so if you're having a different problem from me, go and read it. But these two sentences showed me my mistake:

The uninstall hook must be implemented in the module's .install file. … When hook_uninstall() is called, your module will already be disabled, so its .module file will not be automatically included.

So you have to put the uninstall code in a .install file. It cannot go in .module, because the module will already be disabled when the module is uninstalled, so the .module file will not be loaded.

There are some major performance (you don't want more PHP files loaded than you actually need) and security (uninstalled modules easily get out of date, so you don't want vulnerabilities loaded for code you're not even using) reasons for that.

But it caught me out. So just in case I'm not the only one, I'll own up to this schoolboy error.

Anyone else made a schoolboy error in Drupal that others might benefit from hearing about? Pile into the comments below!

Blog Category: 

Add new comment

Additional Terms