Skip to content

Instantly share code, notes, and snippets.

@aklump
Last active March 30, 2024 21:49
Show Gist options
  • Save aklump/665868d1f1ff2e1d53dedba2c274a6b2 to your computer and use it in GitHub Desktop.
Save aklump/665868d1f1ff2e1d53dedba2c274a6b2 to your computer and use it in GitHub Desktop.
Get the delta on the host entity for a paragraph.
<?php
use Drupal\paragraphs\ParagraphInterface;
/**
* Get the delta on the host entity for a paragraph.
*/
class GetHostDelta {
public function __invoke(ParagraphInterface $paragraph): ?string {
$host = $paragraph->getParentEntity();
$host_field_name = !$host ? '' : $paragraph->get('parent_field_name')->value;
$items = !$host_field_name ? [] : $host->get($host_field_name);
foreach ($items as $item) {
if ($item->get('target_id')->getValue() == $paragraph->id()) {
return (string) $item->getName();
}
}
return NULL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment