### Implement Custom Alias Type Plugin Source: https://context7.com/project/pathauto/llms.txt Implement `AliasTypeInterface` to define a custom alias type for non-entity paths. This example shows how to define the plugin's ID, label, token types, and source prefix. ```php use Drupal\pathauto\Attribute\AliasType; use Drupal\pathauto\AliasTypeInterface; use Drupal\Core\Plugin\PluginBase; /** * Custom alias type for a non-entity path type. */ #[AliasType( id: 'my_custom_type', label: 'My Custom Paths', types: ['my_token_type'], provider: 'mymodule', )] class MyCustomAliasType extends PluginBase implements AliasTypeInterface { public function getLabel(): string { return (string) $this->pluginDefinition['label']; } public function getTokenTypes(): array { return $this->pluginDefinition['types']; } // Returns the URL prefix used to identify and bulk-delete aliases of this type. public function getSourcePrefix(): string { return '/my-custom-path/'; } // Return true if this plugin handles the given object. public function applies($object): bool { return $object instanceof MyCustomEntity; } } ``` -------------------------------- ### Manage Path Aliases with AliasStorageHelperInterface Source: https://context7.com/project/pathauto/llms.txt Use this service to perform direct operations on path aliases, such as saving, loading, counting, and deleting. It abstracts the underlying storage mechanism. ```php /** @var \Drupal\pathauto\AliasStorageHelperInterface $storage */ $storage = \Drupal::service('pathauto.alias_storage_helper'); // Save a new alias. $path = [ 'source' => '/node/42', 'alias' => '/blog/my-article-title', 'language' => 'en', ]; $saved = $storage->save($path); // $saved: ['source' => '/node/42', 'alias' => '/blog/my-article-title', 'pid' => 17, 'langcode' => 'en'] // Load an existing alias by source path. $existing = $storage->loadBySource('/node/42', 'en'); // $existing: ['source' => '/node/42', 'alias' => '/blog/my-article-title', 'pid' => 17, 'langcode' => 'en'] // Returns FALSE if no alias found. // Save with an existing alias to trigger update logic. $storage->save($path, $existing, 'update'); // Count all aliases matching a source path prefix. $count = $storage->countBySourcePrefix('/node/'); // $count: 150 // Count all aliases in the system. $total = $storage->countAll(); // Load all path IDs (PIDs) by source prefix. $pids = $storage->loadBySourcePrefix('/node/'); // Delete all aliases for a source and its sub-paths. $storage->deleteBySourcePrefix('/node/42'); // Delete all aliases for an entity, including default URI variants. $node = \Drupal\node\Entity\Node::load(42); $storage->deleteEntityPathAll($node); // Delete multiple aliases by PID array. $storage->deleteMultiple([17, 18, 19]); // Truncate all aliases (use with caution!). $storage->deleteAll(); // Get the maximum alias length the database schema allows. $maxLen = $storage->getAliasSchemaMaxLength(); // typically 255 ``` -------------------------------- ### Generate Pathauto Aliases Interactively Source: https://context7.com/project/pathauto/llms.txt Use this command to interactively select actions and entity types for generating URL aliases. ```bash drush pathauto:aliases-generate ``` -------------------------------- ### AliasStorageHelperInterface Source: https://context7.com/project/pathauto/llms.txt Abstracts all direct path alias storage operations: saving, loading, counting, and deleting aliases. ```APIDOC ## AliasStorageHelperInterface ### Description Provides an interface for managing path aliases, including saving, loading, counting, and deleting operations. ### Methods - **save(array $path, array $existing = NULL, string $operation = 'insert'): array|bool** Saves a new alias or updates an existing one. - **loadBySource(string $source, string $langcode = NULL): array|bool** Loads an existing alias by its source path and language. - **countBySourcePrefix(string $prefix): int** Counts all aliases matching a source path prefix. - **countAll(): int** Counts all aliases in the system. - **loadBySourcePrefix(string $prefix): array** Loads all path IDs (PIDs) by source prefix. - **deleteBySourcePrefix(string $prefix): void** Deletes all aliases for a source and its sub-paths. - **deleteEntityPathAll($entity): void** Deletes all aliases for a given entity. - **deleteMultiple(array $pids): void** Deletes multiple aliases by their PIDs. - **deleteAll(): void** Truncates all aliases in the system. - **getAliasSchemaMaxLength(): int** Gets the maximum alias length allowed by the database schema. ### Example Usage ```php /** @var \Drupal\pathauto\AliasStorageHelperInterface $storage */ $storage = \Drupal::service('pathauto.alias_storage_helper'); // Save a new alias. $path = [ 'source' => '/node/42', 'alias' => '/blog/my-article-title', 'language' => 'en', ]; $saved = $storage->save($path); // Load an existing alias. $existing = $storage->loadBySource('/node/42', 'en'); // Update an existing alias. $storage->save($path, $existing, 'update'); // Count aliases. $count = $storage->countBySourcePrefix('/node/'); $total = $storage->countAll(); // Delete aliases. $storage->deleteBySourcePrefix('/node/42'); $node = \Drupal\node\Entity\Node::load(42); $storage->deleteEntityPathAll($node); $storage->deleteMultiple([17, 18, 19]); $storage->deleteAll(); // Get max length. $maxLen = $storage->getAliasSchemaMaxLength(); ``` ``` -------------------------------- ### Manage Pathauto State for Entities Source: https://context7.com/project/pathauto/llms.txt Control automatic alias generation for individual entities by setting their pathauto state. Use PathautoState::CREATE to enable and PathautoState::SKIP to disable. Bulk operations and key computation are also supported. ```php use Drupal\pathauto\PathautoState; $node = \Drupal\node\Entity\Node::load(42); // Read the current state for an entity's path field item. $state = $node->path->pathauto; // returns PathautoState::CREATE or PathautoState::SKIP // Disable automatic alias generation for this entity. $node->path->pathauto = PathautoState::SKIP; $node->save(); // Re-enable automatic alias generation. $node->path->pathauto = PathautoState::CREATE; $node->save(); // Bulk-delete aliases only for entities that had auto-generated aliases. // $pids_by_id: array of [entity_id => path_alias_pid] PathautoState::bulkDelete('node', [42 => 17, 43 => 18]); // Compute the key-value store key for an entity ID (hashed if >128 chars). $key = PathautoState::getPathautoStateKey('my-very-long-string-id'); ``` -------------------------------- ### Manage Pathauto Patterns with PathautoPattern Entity Source: https://context7.com/project/pathauto/llms.txt Create, load, update, and delete Pathauto pattern configuration entities programmatically. These define how aliases are generated for different entity types. ```php use Drupal\pathauto\Entity\PathautoPattern; // Create and save a new pattern programmatically. $pattern = PathautoPattern::create([ 'id' => 'blog_nodes', 'label' => 'Blog nodes', 'type' => 'canonical_entities:node', 'pattern' => 'blog/[node:title]', 'weight' => -5, ]); $pattern->save(); // Load and inspect an existing pattern. /** @var \Drupal\pathauto\PathautoPatternInterface $pattern */ $pattern = \Drupal::entityTypeManager() ->getStorage('pathauto_pattern') ->load('blog_nodes'); echo $pattern->getPattern(); // 'blog/[node:title]' echo $pattern->getType(); // 'canonical_entities:node' echo $pattern->getWeight(); // -5 // Change the pattern string. $pattern->setPattern('articles/[node:title]'); $pattern->save(); // Add a selection condition to restrict the pattern to a specific bundle. $condition_id = $pattern->addSelectionCondition([ 'id' => 'node_type', 'bundles' => ['blog' => 'blog'], 'negate' => FALSE, 'context_mapping' => ['node' => 'node'], ]); $pattern->save(); // Check if the pattern applies to a specific entity. $node = \Drupal\node\Entity\Node::load(42); if ($pattern->applies($node)) { echo 'Pattern applies to this node.'; } // Enable / disable a pattern. $pattern->enable()->save(); $pattern->disable()->save(); ``` -------------------------------- ### Bulk Generate URL Aliases (Drush) Source: https://context7.com/project/pathauto/llms.txt Use the `pathauto:aliases-generate` Drush command for bulk alias creation, update, or regeneration. Specify the action and entity types to process. ```bash # Generate aliases for all un-aliased content of all types. drush pathauto:aliases-generate create all # Generate aliases only for un-aliased nodes. drush pathauto:aliases-generate create canonical_entities:node # Update existing aliases for all taxonomy terms. drush pathauto:aliases-generate update canonical_entities:taxonomy_term # Regenerate ALL aliases (create + update) for nodes and users. drush pathauto:aliases-generate all canonical_entities:node,canonical_entities:user ``` -------------------------------- ### Pathauto Module Default Configuration Source: https://context7.com/project/pathauto/llms.txt Default settings for the Pathauto module, including enabled entity types, punctuation handling, and alias length limits. These are stored in `pathauto.settings.yml`. ```yaml # config/install/pathauto.settings.yml — default values # Entity types that have the 'path' base field added by Pathauto. enabled_entity_types: - user # Punctuation handling (0 = remove, 1 = replace with separator, 2 = leave). punctuation: hyphen: 1 # replace hyphens with separator # Whether to show verbose alias-creation/update messages. verbose: false # The separator character inserted between words. separator: '-' # Maximum total alias length (characters). max_length: 150 # Maximum length of a single path component between slashes. max_component_length: 100 # Transliterate non-ASCII characters to ASCII equivalents. transliterate: true # Strip all non-ASCII characters (applied after transliteration). reduce_ascii: false # Convert alias to lowercase. case: true # Space-separated stop words to strip from aliases. ignore_words: 'a, an, as, at, before, but, by, for, from, is, in, into, like, of, off, on, onto, per, since, than, the, this, that, to, up, via, with' # What to do when an existing alias is updated: # 0 = do nothing, 1 = create new (keep old), 2 = replace old alias. update_action: 2 # Token types whose output is treated as already-clean URL components. safe_tokens: - alias - path - join-path - login-url - url - url-brief ``` -------------------------------- ### PathautoState Class Methods Source: https://context7.com/project/pathauto/llms.txt Provides methods for managing the state of automatic alias generation for entities. ```APIDOC ## PathautoState Class Methods ### Description Provides methods for managing the state of automatic alias generation for entities. ### Methods - `PathautoState::bulkDelete(string $entity_type_id, array $pids_by_id)`: Bulk-deletes aliases for entities that had auto-generated aliases. - `PathautoState::getPathautoStateKey(string $entity_id)`: Computes the key-value store key for an entity ID. ### Constants - `PathautoState::CREATE = 1`: Indicates that an alias should be automatically generated. - `PathautoState::SKIP = 0`: Indicates that automatic alias generation should be skipped. ``` -------------------------------- ### PathautoPatternInterface Source: https://context7.com/project/pathauto/llms.txt Represents a Pathauto pattern configuration entity. ```APIDOC ## PathautoPatternInterface ### Description Represents a Pathauto pattern configuration entity, which associates a token pattern string with an alias type, optional selection conditions, and a priority weight. These are managed at `admin/config/search/path/patterns`. ### Methods - **getPattern(): string** Gets the pattern string. - **setPattern(string $pattern): Sets the pattern string. - **getType(): string** Gets the alias type. - **getWeight(): int** Gets the weight of the pattern. - **addSelectionCondition(array $condition): string** Adds a selection condition to the pattern and returns its ID. - **applies($entity): bool** Checks if the pattern applies to a specific entity. - **enable(): Enables the pattern. - **disable(): Disables the pattern. - **save(): Saves the pattern configuration. ### Example Usage ```php use Drupal\pathauto\Entity\PathautoPattern; // Create and save a new pattern. $pattern = PathautoPattern::create([ 'id' => 'blog_nodes', 'label' => 'Blog nodes', 'type' => 'canonical_entities:node', 'pattern' => 'blog/[node:title]', 'weight' => -5, ]); $pattern->save(); // Load and inspect an existing pattern. $pattern = \Drupal::entityTypeManager() ->getStorage('pathauto_pattern') ->load('blog_nodes'); // Modify and save the pattern. $pattern->setPattern('articles/[node:title]'); $pattern->addSelectionCondition([ 'id' => 'node_type', 'bundles' => ['blog' => 'blog'], 'negate' => FALSE, 'context_mapping' => ['node' => 'node'], ]); $pattern->save(); // Check if the pattern applies to an entity. $node = \Drupal\node\Entity\Node::load(42); if ($pattern->applies($node)) { echo 'Pattern applies to this node.'; } // Enable/disable a pattern. $pattern->enable()->save(); $pattern->disable()->save(); ``` ``` -------------------------------- ### pathauto:aliases-generate Source: https://context7.com/project/pathauto/llms.txt Bulk generates URL aliases via a Drush batch process. ```APIDOC ## pathauto:aliases-generate (`pag`) ### Description Generates URL aliases in bulk via a Drush batch process. Supports three actions: `create` (only un-aliased), `update` (only already-aliased), or `all`. ### Usage `drush pathauto:aliases-generate [action] [entity_type_ids...]` ### Parameters - **action** (`string`): The action to perform. Can be `create`, `update`, or `all`. - **entity_type_ids...** (`string`): A comma-separated list of entity type IDs for which to generate aliases. Use `all` to target all entity types. ``` -------------------------------- ### Sanitize Strings and Aliases with AliasCleaner Source: https://context7.com/project/pathauto/llms.txt Use the 'pathauto.alias_cleaner' service to sanitize strings for URL use. This includes transliteration, punctuation handling, whitespace normalization, and length limits. It can clean individual segments or full alias paths. ```php /** @var \Drupal\pathauto\AliasCleanerInterface $cleaner */ $cleaner = \Drupal::service('pathauto.alias_cleaner'); // Clean an individual string segment (e.g. a token replacement value). $clean = $cleaner->cleanString('Hello, World! (2024)', ['langcode' => 'en']); // $clean: 'hello-world-2024' // Clean an assembled full alias path (trims slashes and separators). $alias = $cleaner->cleanAlias('/blog//hello--world/'); // $alias: 'blog/hello-world' // Remove duplicate/leading/trailing separators from a string. $result = $cleaner->getCleanSeparators('--foo--bar--', '-'); // $result: 'foo-bar' // Get the full list of punctuation characters Pathauto can control. $punctuation = $cleaner->getPunctuationCharacters(); // Returns array keyed by name, e.g.: // ['hyphen' => ['value' => '-', 'name' => 'Hyphen'], 'period' => [...], ...] // Clean token replacement values in-place (used as a token callback). $replacements = ['[node:title]' => 'My Article Title!']; $cleaner->cleanTokenValues($replacements, ['node' => $node], ['langcode' => 'en']); // $replacements: ['[node:title]' => 'my-article-title'] ``` -------------------------------- ### Generate and Update Entity Aliases with PathautoGenerator Source: https://context7.com/project/pathauto/llms.txt Inject the 'pathauto.generator' service to create, update, or return URL aliases for entities. Use 'insert', 'update', or 'return' operations. The 'force' option can override skip flags. ```php // Inject via service container in custom code: /** @var \Drupal\pathauto\PathautoGeneratorInterface $generator */ $generator = \Drupal::service('pathauto.generator'); // Load a node and generate/save its alias on insert. $node = \Drupal\node\Entity\Node::load(42); $result = $generator->createEntityAlias($node, 'insert'); // $result: ['source' => '/node/42', 'alias' => '/blog/my-article-title', 'language' => 'en'] // Update the alias for an existing entity (respects the configured update_action setting). $result = $generator->updateEntityAlias($node, 'update'); // Returns NULL if no pattern matches or pathauto processing is disabled for this entity. // Return what the alias WOULD be without saving it. $alias = $generator->createEntityAlias($node, 'return'); // $alias: '/blog/my-article-title' // Retrieve the matching PathautoPattern for an entity (NULL if none applies). $pattern = $generator->getPatternByEntity($node); if ($pattern) { echo $pattern->getPattern(); // e.g. 'blog/[node:title]' } // Force-update an alias ignoring PathautoState::SKIP flag. $result = $generator->updateEntityAlias($node, 'update', ['force' => TRUE]); // Reset internal pattern caches (useful after config changes in the same request). $generator->resetCaches(); ``` -------------------------------- ### PathautoGeneratorInterface Source: https://context7.com/project/pathauto/llms.txt The central service for generating and persisting URL aliases for entities. It resolves patterns, replaces tokens, cleans the result, and saves it. ```APIDOC ## `pathauto.generator` — PathautoGeneratorInterface ### Description The central service for generating and persisting URL aliases for entities. It resolves the matching pattern for an entity, replaces tokens, cleans the result, and saves it via `AliasStorageHelper`. The `op` parameter controls whether the alias is inserted, updated, returned without saving, or processed as a bulk update. ### Usage Example ```php // Inject via service container in custom code: /** @var \Drupal\pathauto\PathautoGeneratorInterface $generator */ $generator = \Drupal::service('pathauto.generator'); // Load a node and generate/save its alias on insert. $node = \Drupal\node\Entity\Node::load(42); $result = $generator->createEntityAlias($node, 'insert'); // $result: ['source' => '/node/42', 'alias' => '/blog/my-article-title', 'language' => 'en'] // Update the alias for an existing entity (respects the configured update_action setting). $result = $generator->updateEntityAlias($node, 'update'); // Returns NULL if no pattern matches or pathauto processing is disabled for this entity. // Return what the alias WOULD be without saving it. $alias = $generator->createEntityAlias($node, 'return'); // $alias: '/blog/my-article-title' // Retrieve the matching PathautoPattern for an entity (NULL if none applies). $pattern = $generator->getPatternByEntity($node); if ($pattern) { echo $pattern->getPattern(); // e.g. 'blog/[node:title]' } // Force-update an alias ignoring PathautoState::SKIP flag. $result = $generator->updateEntityAlias($node, 'update', ['force' => TRUE]); // Reset internal pattern caches (useful after config changes in the same request). $generator->resetCaches(); ``` ``` -------------------------------- ### Bulk Delete Pathauto URL Aliases Source: https://context7.com/project/pathauto/llms.txt Deletes auto-generated URL aliases in bulk. Specify entity types or 'all'. Use the --purge option to remove manually created aliases as well. ```bash # Delete all auto-generated node aliases (preserves manually created aliases). drush pathauto:aliases-delete canonical_entities:node ``` ```bash # Delete all auto-generated aliases for all types. drush pathauto:aliases-delete all ``` ```bash # Delete ALL aliases including manually created ones (full purge). drush pathauto:aliases-delete all --purge ``` ```bash # Interactive mode (choose types from a multi-select menu). drush pathauto:aliases-delete ``` -------------------------------- ### hook_pathauto_is_alias_reserved() Source: https://context7.com/project/pathauto/llms.txt Allows modules to mark aliases as reserved, preventing Pathauto from using them. ```APIDOC ## hook_pathauto_is_alias_reserved() ### Description Allows modules to prevent Pathauto from using an alias that would conflict with a custom path in the module's own routing or data. ### Parameters - **$alias** (`string`): The alias string to check. - **$source** (`string`): The source path. - **$langcode** (`string`): The language code. ### Returns (`bool`): TRUE if the alias is reserved, FALSE otherwise. ``` -------------------------------- ### AliasCleanerInterface Source: https://context7.com/project/pathauto/llms.txt Sanitizes raw strings and full alias paths for safe use in URLs. Handles transliteration, punctuation replacement/removal, and more. ```APIDOC ## `pathauto.alias_cleaner` — AliasCleanerInterface ### Description Sanitizes raw strings and full alias paths for safe use in URLs. Handles transliteration, punctuation replacement/removal, whitespace normalization, stop-word removal, case conversion, and length truncation. ### Usage Example ```php /** @var \Drupal\pathauto\AliasCleanerInterface $cleaner */ $cleaner = \Drupal::service('pathauto.alias_cleaner'); // Clean an individual string segment (e.g. a token replacement value). $clean = $cleaner->cleanString('Hello, World! (2024)', ['langcode' => 'en']); // $clean: 'hello-world-2024' // Clean an assembled full alias path (trims slashes and separators). $alias = $cleaner->cleanAlias('/blog//hello--world/'); // $alias: 'blog/hello-world' // Remove duplicate/leading/trailing separators from a string. $result = $cleaner->getCleanSeparators('--foo--bar--', '-'); // $result: 'foo-bar' // Get the full list of punctuation characters Pathauto can control. $punctuation = $cleaner->getPunctuationCharacters(); // Returns array keyed by name, e.g.: // ['hyphen' => ['value' => '-', 'name' => 'Hyphen'], 'period' => [...], ...] // Clean token replacement values in-place (used as a token callback). $replacements = ['[node:title]' => 'My Article Title!']; $cleaner->cleanTokenValues($replacements, ['node' => $node], ['langcode' => 'en']); // $replacements: ['[node:title]' => 'my-article-title'] ``` ``` -------------------------------- ### Ensure Alias Uniqueness with AliasUniquifierInterface Source: https://context7.com/project/pathauto/llms.txt Use this service to guarantee that generated URL aliases are unique. It automatically appends suffixes like '-0', '-1' if an alias is already in use. ```php /** @var \Drupal\pathauto\AliasUniquifierInterface $uniquifier */ $uniquifier = \Drupal::service('pathauto.alias_uniquifier'); // Uniquify an alias in-place by reference. $alias = 'blog/my-article-title'; // already taken by another path $uniquifier->uniquify($alias, '/node/99', 'en'); // $alias is now 'blog/my-article-title-0' (or higher suffix if needed) // Check if an alias is reserved (conflicts with an existing path or alias). $reserved = $uniquifier->isReserved('blog/my-article-title', '/node/99', 'en'); // true if a different source already uses this alias ``` -------------------------------- ### hook_pathauto_pattern_alter() Source: https://context7.com/project/pathauto/llms.txt Allows modules to dynamically alter the pattern used before token replacement runs for alias generation. ```APIDOC ## hook_pathauto_pattern_alter() ### Description Allows modules to dynamically swap or modify the pattern used before token replacement runs. ### Parameters - **$pattern** (`\Drupal\pathauto\PathautoPatternInterface`): The pattern object to alter. - **$context** (`array`): An array containing context information about the alias generation process, including 'module' and 'op'. ``` -------------------------------- ### hook_pathauto_punctuation_chars_alter() Source: https://context7.com/project/pathauto/llms.txt Extends or modifies the set of punctuation characters that Pathauto controls. ```APIDOC ## hook_pathauto_punctuation_chars_alter() ### Description Extends or modifies the set of punctuation characters that Pathauto controls (replace with separator, remove, or leave intact). ### Parameters - **& $punctuation** (`array`): An array of punctuation character definitions to alter (passed by reference). ``` -------------------------------- ### Implement Batch Operations for Custom Alias Type Source: https://context7.com/project/pathauto/llms.txt Implement `AliasTypeBatchUpdateInterface` to enable Drush and UI bulk operations for your custom alias type. This includes methods for batch updates and deletions. ```php use Drupal\pathauto\AliasTypeBatchUpdateInterface; use Drupal\pathauto\AliasTypeInterface; use Drupal\Core\Plugin\PluginBase; // Batch update implementation (optional, enables drush/UI bulk operations). class MyCustomAliasType extends PluginBase implements AliasTypeInterface, AliasTypeBatchUpdateInterface { public function batchUpdate($action, & $context): void { // Query entities, call pathauto.generator->updateEntityAlias() in chunks. $ids = $this->getUnaliasedIds($context); foreach ($ids as $id) { $entity = MyCustomEntity::load($id); \Drupal::service('pathauto.generator')->updateEntityAlias($entity, $action); } } public function batchDelete(& $context): void { \Drupal::service('pathauto.alias_storage_helper') ->deleteBySourcePrefix($this->getSourcePrefix()); } } ``` -------------------------------- ### AliasUniquifierInterface Source: https://context7.com/project/pathauto/llms.txt Ensures generated aliases are unique by appending suffixes if necessary. ```APIDOC ## AliasUniquifierInterface ### Description Provides an interface for ensuring that generated URL aliases are unique, preventing conflicts by appending numerical suffixes when necessary. ### Methods - **uniquify(string &$alias, string $source, string $langcode): void** Modifies the given alias string in-place to ensure it is unique for the specified source and language. - **isReserved(string $alias, string $source, string $langcode): bool** Checks if the given alias is already reserved (i.e., conflicts with an existing path or alias for a different source). ### Example Usage ```php /** @var \Drupal\pathauto\AliasUniquifierInterface $uniquifier */ $uniquifier = \Drupal::service('pathauto.alias_uniquifier'); // Ensure an alias is unique. $alias = 'blog/my-article-title'; // Assume this is already taken $uniquifier->uniquify($alias, '/node/99', 'en'); // $alias will be modified to 'blog/my-article-title-0' or similar if needed. // Check if an alias is reserved. $reserved = $uniquifier->isReserved('blog/my-article-title', '/node/99', 'en'); ``` ``` -------------------------------- ### hook_pathauto_alias_alter() Source: https://context7.com/project/pathauto/llms.txt Allows modules to modify the final alias string after token replacement but before it is saved. ```APIDOC ## hook_pathauto_alias_alter() ### Description Allows modules to modify the final alias string after tokens have been replaced and the string has been cleaned, but before it is uniquified and saved. ### Parameters - **&$alias** (`string`): The alias string to alter (passed by reference). - **&$context** (`array`): An array containing context information about the alias generation process. ``` -------------------------------- ### Alter Pathauto Pattern Before Generation Source: https://context7.com/project/pathauto/llms.txt Use hook_pathauto_pattern_alter() to dynamically modify the pattern used for alias generation before token replacement. This is useful for conditional pattern changes based on context. ```php /** * Implements hook_pathauto_pattern_alter(). */ function mymodule_pathauto_pattern_alter(\Drupal\pathauto\PathautoPatternInterface $pattern, array $context) { // On update operations, replace [node:created:*] tokens with [node:updated:*]. if ($context['module'] === 'node' && $context['op'] === 'update') { $pattern->setPattern( preg_replace('/\[node:created(\:.*)?\]/', '[node:updated$1]', $pattern->getPattern()) ); } // Force a specific pattern for a particular bundle. if ($context['bundle'] === 'landing_page') { $pattern->setPattern('landing/[node:title]'); } } ``` -------------------------------- ### Add or Remove Punctuation Rules Source: https://context7.com/project/pathauto/llms.txt Extend or modify Pathauto's punctuation handling with hook_pathauto_punctuation_chars_alter(). This hook allows adding new punctuation characters or removing existing ones from Pathauto's control. ```php /** * Implements hook_pathauto_punctuation_chars_alter(). */ function mymodule_pathauto_punctuation_chars_alter(array & $punctuation) { // Add the trademark symbol to Pathauto's punctuation controls. $punctuation['trademark'] = ['value' => '™', 'name' => t('Trademark symbol')]; // Remove the dollar sign from Pathauto's controls (leave it as-is in aliases). unset($punctuation['dollar']); } ``` -------------------------------- ### Mark Aliases as Reserved Source: https://context7.com/project/pathauto/llms.txt Use hook_pathauto_is_alias_reserved() to prevent Pathauto from using an alias that conflicts with custom paths managed by your module. It should return TRUE if the alias is reserved. ```php /** * Implements hook_pathauto_is_alias_reserved(). */ function mymodule_pathauto_is_alias_reserved($alias, $source, $langcode) { // Reserve all aliases that match paths in our custom table. return (bool) \Drupal::database() ->query("SELECT 1 FROM {mymodule_paths} WHERE path = :path", [':path' => $alias]) ->fetchField(); } ``` -------------------------------- ### Alter Alias After Token Replacement Source: https://context7.com/project/pathauto/llms.txt Implement hook_pathauto_alias_alter() to modify the generated alias string after token replacement and cleaning, but before it is made unique and saved. This allows for suffixing or prefixing aliases. ```php /** * Implements hook_pathauto_alias_alter(). */ function mymodule_pathauto_alias_alter(&$alias, array &$context) { // Append .html suffix to all generated aliases. $alias .= '.html'; // Prefix all taxonomy term aliases with 'topic/'. if ($context['module'] === 'taxonomy') { $alias = 'topic/' . $alias; } } ``` -------------------------------- ### hook_path_alias_types_alter() Source: https://context7.com/project/pathauto/llms.txt Modifies the registered alias type plugin definitions. ```APIDOC ## hook_path_alias_types_alter() ### Description Modifies the registered alias type plugin definitions, for example to override labels or disable certain types. ### Parameters - **& $definitions** (`array`): An array of alias type plugin definitions to alter (passed by reference). ``` -------------------------------- ### Alter Alias Type Plugin Definitions Source: https://context7.com/project/pathauto/llms.txt Modify alias type plugin definitions using hook_path_alias_types_alter(). This can be used to disable specific alias types or override their labels. ```php /** * Implements hook_path_alias_types_alter(). */ function mymodule_path_alias_types_alter(array & $definitions) { // Disable the user alias type entirely. unset($definitions['canonical_entities:user']); // Override the label for node aliases. if (isset($definitions['canonical_entities:node'])) { $definitions['canonical_entities:node']['label'] = t('Content (custom label)'); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.