Ryan Bateman logoRyan BatemanFull Stack Web Developer

Tutorial: Removing Paragraphs Types with Existing Content

23 October, 2017 - 6:07 PM

Paragraphs has quickly become an integral part of my sitebuilding workflow. So much so, in fact, that it's hard to imagine scaffolding out a new site without it. However, there are a few quirks in the module that can cause problems.

In particular, sitebuilders often run into problems when deleting a paragraph type that has previously been used in content, which returns an error such as:

MyParagraph type is used by X pieces of content on your site.
You may not remove MyParagraph type until you have removed all from the content.

The usual response for most sitebuilders in this situation is to say 'ah, I should probably go delete any nodes that have that paragraph type in use', but unfortunately that response only makes the issue worse.

Due to the fact that paragraphs treats each instance of a paragraph type as a unique entity and stores them separately in their own entity reference in the DB, deleting the node doesn't actually get rid of any of the content. Instead, it removes the node with the entity reference on it, so now it's technically impossible to go in and delete the actual entity from the paragraphs entity reference form.

This issue is well documented and has several open issues in the queue, but in the meantime we need to figure out a way to get rid of a paragraph type that already had data without completely nuking our content and starting over.

Here is a quick php scrip that can help:

<?php
$paragraphType = 'your_paragraph_machine_name';
//define machine name you want to snag
$paragraphs = \Drupal::entityTypeManager() 
//use entityTypeManager API
    ->getStorage('paragraph')
    //get from paragraph storage
    ->loadByProperties(array('type' => $paragraphType));
    //get instances of paragraphs of type defined in var

foreach ($paragraphs as $paragraph) {
//for each of the wiggly little child paragraphs
    $paragraph->delete();
    //blast em
}

All this script does is use the entityTypeManager API to grab all instances of the paragraph type in storage and then delete them each in a for loop.

To run the script, place in a file called paragraphs-purge.php at your Drupal root, then execute a

drush php-script paragraphs-purge.php

at which point you should be able to delete the Paragraph Type without any issue.

Lastly, make sure to remove the script from your Drupal root once you're done using it, just for safety's sake.

Invert color scheme