Last active
September 12, 2024 10:48
-
-
Save antmbraun/3ae4f22c6ddd1de2b959284c0ec74e3f to your computer and use it in GitHub Desktop.
Get all instances of paragraphs in Drupal 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Recursive should return top parent entity, not only node.