I have a custom module, mymodule, that will create custom blocks, block_test and block_test2 on mymodule_install().

When the module is uninstalled, I want to remove any blocks created by mymodule. How would I delete the block generated by a module being uninstalled?

drush command (local dev):

drush pmu mymodule -yv


function mymodule_uninstall() {
  // Delete Blocks generated by module.

  /** @var \Drupal\Core\Entity\EntityStorageInterface $block_storage */
  $block_storage = \Drupal::service('entity_type.manager')->getStorage('block');
  /** @var \Drupal\block\Entity\Block[] $blocks */
  $blocks = $block_storage->loadMultiple();
  foreach ($blocks as $block) {
    // I am stuck here. 
  • What kind of blocks? content blocks? You could try using enforced config dependencies, see drupal.org/node/2404447
    – Berdir
    Aug 3, 2018 at 22:17
  • @Berdir the boxes are of basic block types that come with Core Aug 3, 2018 at 23:05

1 Answer 1


Yes, then the best thing would be to follow the enforced config dependencies part above, if you create the content blocks with a fixed uuid then you can just put the block config entities in your config/install folder, with the config dependencies as explained there and it should be uninstalled automatically.

At least the config entities, if you want to delete the block_content entities too then load them by UUID with $block_content = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', 'YOUR_UUID'); $block_content->delete()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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