diff --git a/core/modules/serialization/serialization.services.yml b/core/modules/serialization/serialization.services.yml index dca6094..eb2690a 100644 --- a/core/modules/serialization/serialization.services.yml +++ b/core/modules/serialization/serialization.services.yml @@ -33,7 +33,7 @@ services: # this modules generic field item normalizer. # @todo Find a better way for this in https://www.drupal.org/node/2575761. - { name: normalizer, priority: 8 } - arguments: ['@entity.repository'] + arguments: ['@entity.repository', '@router.route_provider'] serialization.normalizer.field_item: class: Drupal\serialization\Normalizer\FieldItemNormalizer tags: diff --git a/core/modules/serialization/src/Normalizer/EntityReferenceFieldItemNormalizer.php b/core/modules/serialization/src/Normalizer/EntityReferenceFieldItemNormalizer.php index ea2e020..80c7bdb 100644 --- a/core/modules/serialization/src/Normalizer/EntityReferenceFieldItemNormalizer.php +++ b/core/modules/serialization/src/Normalizer/EntityReferenceFieldItemNormalizer.php @@ -3,6 +3,7 @@ namespace Drupal\serialization\Normalizer; use Drupal\Core\Entity\EntityRepositoryInterface; +use Drupal\Core\Routing\RouteProvider; use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem; use Symfony\Component\Serializer\Exception\InvalidArgumentException; use Symfony\Component\Serializer\Exception\UnexpectedValueException; @@ -27,13 +28,23 @@ class EntityReferenceFieldItemNormalizer extends FieldItemNormalizer { protected $entityRepository; /** + * The route provider. + * + * @var \Drupal\Core\Routing\RouteProvider + */ + protected $routeProvider; + + /** * Constructs a EntityReferenceFieldItemNormalizer object. * * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository * The entity repository. + * @param \Drupal\Core\Routing\RouteProvider $route_provider + * The route provider. */ - public function __construct(EntityRepositoryInterface $entity_repository) { + public function __construct(EntityRepositoryInterface $entity_repository, RouteProvider $route_provider) { $this->entityRepository = $entity_repository; + $this->routeProvider = $route_provider; } /** @@ -51,7 +62,13 @@ public function normalize($field_item, $format = NULL, array $context = []) { // Add a 'url' value if there is a reference and a canonical URL. Hard // code 'canonical' here as config entities override the default $rel // parameter value to 'edit-form. - if ($url = $entity->url('canonical')) { + // Since some entity types don't have a canonical URL, we check the + // route provider to ensure that it does before we try generating a + // canonical URL. + if ( + $this->routeProvider->getRouteByName('entity.' . $values['target_type'] . '.canonical') && + $url = $entity->url('canonical') + ) { $values['url'] = $url; } }