#! code: Drupal 10: Using Parameter Converters To Create Paths For Custom Entities

Drupal's path system gives authors the ability to override the path of an item of content. Whilst the internal path of a page might be "/node/1" the external path can be anything you want, and can be set when editing the item of content.

The addition of the Path Auto module makes this change of path easy for your users by using patterns and automatically generating paths based on the data contained within the content item. You might want to use a path that contains the type of entity being presented, what category it was added to, and even the title of the item of content.

This system creates powerful search engine friendly URLs that can add keywords to the paths that Drupal uses to find content.

When building custom entities there are a few things you need to do in order to add Path Auto functionality. It must contain a 'canonical' link that points to the entity and be a fieldable entity with a field called 'path'. A canonical link always points to the basic path of the content entity, which would be "/node/1" for all content type entities.

Outside of the Path Auto module there are a number of internal classes called parameter converters that implement the core \Drupal\Core\ParamConverter\ParamConverterInterface interface and are used to convert an argument within a path into an entity object. This object is then passed upstream to the form or controller that will be using the entity.

Without the parameter converter in place you would have to accept a value to the form or controller that you would then have to convert into an entity of some kind. This can add a lot more code to the those classes that wouldn't be needed as they need to know how to load the entity and also what to do if the entity doesn't exist.

In this article I will create a content entity and then show how to generate custom paths to that entity in via a custom parameter converter class.

Read more

PubDate

Tags