Altering the URL alias for External Entities

So simple and yet so hard to figure it out without grep Posted by Toby on Wed 4 Sept. 2019

The External Entities module for Drupal 8 is rather good at allowing you to import external data items as entities to use as content and for searching. But, like a lot of Drupal contrib stuff, it's in flux and not yet available as a stable version and the documentation isn't all there (that holds true for a lot of stable Drupal contrib stuff too).

One thing it omits (which through the judicious use of grep and crawling class hierarchies I've found) is how to alter the URLs of the entities so that you're not stuck with /{type}/{id}.

Now I've discovered how to sort out the bit before the {id} but not yet tried to find out how to replace the ID with the title. If the project I'm one requires it I may revisit this.

So how do you do it? Well the thing seems to be that you need to implement hook_entity_type_alter() and alter the links array like this (using the Wikipedia example:

/**
 * Implements hook_entity_type_alter().
 */
function example_entity_type_alter(array &$entity_types) {
  foreach ($entity_types as $type => $contentEntityType) {
    switch ($type) {
      case 'wikipage':
        $entity_types[$type]->setLinkTemplate('collection', '/wikipedia/articles');
        $entity_types[$type]->setLinkTemplate('canonical', '/wikipedia/articles/{wikipage}');
        break;
    }
  }
}

As always clear all the caches after doing this to make sure it kicks in.