Member-only story

Cómo Modificar una Ruta en Drupal Antes de Guardar el Contenido

Cuando necesitas una lógica personalizada para la generación de URL

Sergio Guardiola Herrador
2 min readOct 1, 2024
Photo by Remotar Jobs on Unsplash

Al utilizar el módulo pathauto, lo mejor es configurar los patrones en esta URL: admin/config/search/path/patterns y luego exportarlos a configuración. Sin embargo, es posible que no sea suficiente si necesitas implementar una lógica personalizada para la generación de URL.

Para ello, puedes utilizar hook_pathauto_alias_alter, que altera los alias generados automáticamente por pathauto antes de guardar el contenido.

Aquí hay un ejemplo de algo que tuve que hacer recientemente.:

/**
* Implements hook_pathauto_alias_alter().
*/
function custom_module_pathauto_alias_alter(string &$alias, array &$context) {
// Ensure this is triggered for node content.
if ($context['module'] == 'node' && isset($context['data']['node'])) {
$node = $context['data']['node'];
// Check if the node has 'islands' field and it's not empty.
if ($node->hasField('islands') && !$node->get('islands')->isEmpty()) {
// Get the taxonomy term ID.
$term_id = $node->get('islands')->target_id;
// Load the taxonomy term entity to get its name.
$term = \Drupal\taxonomy\Entity\Term::load($term_id);
if ($term) {
// Get the taxonomy term…

--

--

Sergio Guardiola Herrador
Sergio Guardiola Herrador

Written by Sergio Guardiola Herrador

I write articles in English and Spanish, mostly about programming, technology, travel, money, investing. You can find me here: https://sergioguardiola.net

No responses yet