Skip to content

Instantly share code, notes, and snippets.

@antmbraun
Last active January 26, 2024 18:54
Show Gist options
  • Save antmbraun/3ae4f22c6ddd1de2b959284c0ec74e3f to your computer and use it in GitHub Desktop.
Save antmbraun/3ae4f22c6ddd1de2b959284c0ec74e3f to your computer and use it in GitHub Desktop.
Get all instances of paragraphs in Drupal 8
$entity_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
$query = \Drupal::entityQuery('paragraph')
->condition('type', "paragraph_type_machine_name")
->accessCheck(false);
$results = $query->execute();
$hosted_paragraphs_found = [];
$orphaned_paragraphs_found = [];
if (!empty($results)) {
if(!empty($paragraph_entities = $entity_storage->loadMultiple($results))) {
foreach ($paragraph_entities as $paragragaph_entity) {
if ($root_parent = recursivelyGetParagraphRootParent($paragragaph_entity)) {
$root_parent_id = $root_parent->id();
if (!key_exists( $root_parent_id, $hosted_paragraphs_found )) {
$hosted_paragraphs_found[$root_parent_id] = 1;
}
else {
$hosted_paragraphs_found[$root_parent_id]++;
}
}
else {
$orphaned_paragraphs_found[] = $paragragaph_entity->id();
}
}
}
}
else {
echo "No instances found!";
}
if ( !empty($hosted_paragraphs_found) ) {
echo "<h2>Paragraphs found!</h2>";
echo "<h3>Host entity ID (count of paragraphs found)</h3>";
echo "<ol>";
foreach ($hosted_paragraphs_found as $root_entity_id => $count) {
echo '<li><a href="/node/' . $root_entity_id . '">' .$root_entity_id . '</a> (' . $count . ')</li>';
}
echo "</ol>";
}
if ( !empty($orphaned_paragraphs_found) ) {
foreach ($orphaned_paragraphs_found as $orphaned_paragraph_id) {
echo "<ol>";
echo "<li>Orphaned paragraph found. Paragraph entity id = $orphaned_paragraph_id</li>";
echo "</ol>";
}
}
// Returns the root node parent of a paragraph entity, or if orphaned returns false.
function recursivelyGetParagraphRootParent($entity) {
if ($entity && $entity->getEntityType()->id() == "node") {
return $entity;
}
elseif ($entity && $entity->getEntityType()->id() !== "node") {
$parent = $entity->getParentEntity();
return recursivelyGetParagraphRootParent($parent);
}
else {
return false;
}
}
@serotonine
Copy link

Thank a lot for this ! it helped me a lot !

@Nikit
Copy link

Nikit commented Nov 9, 2022

Recursive should return top parent entity, not only node.

@Blushu
Copy link

Blushu commented Jan 26, 2024

works like a dream, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment