Fall back to 'edit-form' as default $rel in EntityBase::toUrl()

Created on 1 July 2023, over 1 year ago
Updated 1 March 2024, 10 months ago

Problem/Motivation

It is valid for an entity type not to specify a canonical link. If you call $entity->toUrl() on an entity of that type, it will fail with a

No link template 'canonical' found for the '...' entity type

exception.

If you explicitly dealing with an entity type of that type, just calling $entity->toUrl() like that might be considered a bug, as you should instead do $entity->toUrl('edit-form') (assuming there is an edit-form link) or whatever other link you want to link to, but there is a lot of code in core that generically deals with entities of any type and just wants to output "a link" to an entity. Code like that currently breaks with entities without a canonical link.

See 📌 [meta] Improve support for entity types without a canonical link Needs work for more context, but I think the moist poignant example is the cancel URL of entity delete forms (see Drupal/Core/Entity/EntityDeleteFormTrait::getCancelUrl():

      // Otherwise fall back to the default link template.
      return $entity->toUrl();

The comment notes that it does not really care, whether the canonical link template is used or not, but it needs to link somewhere. It seems unfortunate to require EntityDeleteFormTrait to explicitly check the availability of various link templates. Since we have chosen to make $rel optional, I think we should try to actually make that work also for entities without a canonical link.

Steps to reproduce

1. Create an entity type without a canonical link and provide the default delete form used in core.
2. Expect the delete form to work.
3. Frown, because the delete form throws an exception.

Proposed resolution

In Entity::toUrl(), if no $rel is passed explicitly, check if no canonical link exists, but edit-form does and in that case fall back to edit-form.

Remaining tasks

Review the change record

User interface changes

-

API changes

EntityBase::toUrl() works without specifying $rel for entities without a canonical link.

Data model changes

-

Release notes snippet

📌 Task
Status

Fixed

Version

11.0 🔥

Component
Entity 

Last updated about 15 hours ago

Created by

🇩🇪Germany tstoeckler Essen, Germany

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024