I programmatically created a content type during a module installation (using field storage configuration).
I want to delete that content type while uninstalling the module.
Is there any way to do this with Drupal 8?
Just make sure that the node type depends on your your module, then Drupal will delete it automatically for you.
See node.type.book.yml in the book module for an example, this is the relevant part:
dependencies:
enforced:
module:
- book
Note that users will have to delete all content of that type before they can uninstall the module then.
Note that users will have to delete all content of that type before they can uninstall the module then.
In my case the content type is deleted when uninstalling the module. But deletion of the custom content (nodes) is not enforced. To achieve this the custom module should implement ModuleUninstallValidatorInterface
.
book
module is a good example of how to make sure that a module may not be uninstalled if there is still related content. A ProxyClass
is also required if copying Book's services.yml
file. In that case the following command will be found useful: php core/scripts/generate-proxy-class.php 'Drupal\custom_module\CustomModuleUninstallValidator' "modules/custom/custom_module/src"
This seems to do it for me.
$content_type = \Drupal::entityManager()->getStorage('node_type')->load('MACHINE_NAME_OF_TYPE');
$content_type->delete();
drupal snippet --code='$content_type = \Drupal::entityManager()->getStorage("node_type")->load("MACHINE_NAME_OF_TYPE"); $content_type->delete();'
To trigger some action upon uninstallation of a module you have to implement hook_uninstall
in your module's *.install
file. Prior to deleting the content type you might want to ensure all nodes of that content type got deleted as well. Finally, after uninstalling the module and having the content type deleted don't forget to export the updated config.
/**
* Place a short description here.
*/
function MYMODULE_uninstall() {
// Delete all nodes of given content type.
$storage_handler = \Drupal::entityTypeManager()
->getStorage('node');
$nodes = $storage_handler->loadByProperties(['type' => 'MACHINE_NAME_OF_TYPE']);
$storage_handler->delete($nodes);
// Delete content type.
$content_type = \Drupal::entityTypeManager()
->getStorage('node_type')
->load('MACHINE_NAME_OF_TYPE');
$content_type->delete();
}
bundle
of MACHINE_NAME_OF_TYPE
, like the node-id query based answer does, or not? I mean, that seems to be somewhat expensive (if there are a lot of NIDs) and I would like to use this solution when possible.
Commented
Jun 29, 2019 at 11:13