Drupal - How to delete a content type, programmatically?

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.


This seems to do it for me.

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

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) {
    \Drupal\node\Entity\Node::load($nid)->delete();
  }
}

Tags:

Nodes

8