Link checker now provides a link parent entity resolver plugin type (#[LinkParentEntityResolver]) for resolving the parent of a fieldable entity. The RootEntityResolverInterface service uses these plugins to walk an entity hierarchy until it reaches the root entity.
Link checker includes a resolver for Paragraphs. Modules with other nested entity types can provide their own resolver:
namespace Drupal\my_module\Plugin\LinkParentEntityResolver;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\linkchecker\Attribute\LinkParentEntityResolver;
use Drupal\linkchecker\Plugin\LinkParentEntityResolverInterface;
#[LinkParentEntityResolver(
id: 'my_entity',
label: new TranslatableMarkup('My entity'),
entity_types: ['my_entity'],
)]
class MyEntityParentEntityResolver extends PluginBase implements LinkParentEntityResolverInterface {
public function getParentEntity(FieldableEntityInterface $entity, string $langcode): ?FieldableEntityInterface {
$parent = $entity->getHostEntity();
return $parent instanceof FieldableEntityInterface ? $parent : NULL;
}
}
Resolvers should return NULL when no parent can be resolved and should not perform access checks. When applicable, they should return the parent translation matching $langcode.
The root entity can also be resolved directly using the service:
$root = \Drupal::service(\Drupal\linkchecker\RootEntityResolverInterface::class)
->resolveRootEntity($entity, $langcode);
The language code is optional and defaults to the entity's language. If no parent can be resolved, the original entity is returned.
LinkCheckerLinkInterface::getRootParentEntity() and the "Page entity label" and "Page entity link" Views fields use this service.
From 2.2.0, a resolver plugin can also find child entities. See Link parent entity resolver plugins can find child entities.