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:

      - book

Note that users will have to delete all content of that type before they can uninstall the module then.


This seems to do it for me.

$content_type = \Drupal::entityManager()->getStorage('node_type')->load('MACHINE_NAME_OF_TYPE');

Not having enough credit to comment, I will put it here:

@Berdir, it seems to me that enforcing the module in node.type.custom.yml file is not sufficient to enforce the deletion of the nodes when uninstalling

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 the ModuleUninstallValidatorInterface.

When implemented the custom module can not be uninstalled before the custom nodes are deleted. The select box will be de-activated.

Instead of implementing the Interface I am doing it dirty by deleting the nodes in hook_uninstall():

function MYMODULE_uninstall() {

  // Delete custom_type nodes when uninstalling.
  $query = \Drupal::entityQuery('node')
    ->condition('type', 'custom_type');
  $nids = $query->execute();
  // debug($nids);
  foreach ($nids as $nid) {

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()
  $nodes = $storage_handler->loadByProperties(['type' => 'MACHINE_NAME_OF_TYPE']);

  // Delete content type.
  $content_type = \Drupal::entityTypeManager()
  • Will this delete any 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. – Top-Master Jun 29 at 11:13
  • 1
    @Top-Master – I updated my answer. It needs an extra step to delete all nodes first. – leymannx Jun 29 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.