Germain
Germain

Reputation: 13

Drupal 8 | Wrong alias used

Bonjour,

I have a problem on Drupal 8 that I can't solve, that's why I'm calling on you.

I have 2 aliases for the same node :

I have a block_1 that only appears on the " /public/* " pages and a block_2 on the " /pro/* " pages.

When I access to the url "/pro/event/10", block_1 is displayed and not block_2.

I conclude that Drupal selects the alias "/public/event/10" (probably the first one he finds) while I'm on the page "/pro/event/10".

How can I programmatically tell Drupal the right alias to use?

Thank you in advance for your help.

Upvotes: 0

Views: 172

Answers (2)

Germain
Germain

Reputation: 13

Here is the code if it can help someone

class OOutboundPathProcessor implements OutboundPathProcessorInterface 
{
    function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) 
    {
        // Only for nodes
        if (!isset($options['entity_type']) OR $options['entity_type'] !== 'node') 
        {
            return $path;
        }

        // Get current 'space'
        $espace = \Drupal::service('session')->get('espace');   

        // Get the node to process
        $node = $options['entity'];

        // New path
        $str_path = "/%s/%s/%s";
        $new_path = sprintf($str_path, $espace, $node->bundle(), $node->id());

        // Check new path
        $isValid = \Drupal::service('path.validator')->isValid($new_path);

        if ($isValid === true) return $new_path;

        return $path;
    }
}

Upvotes: 1

gue
gue

Reputation: 1138

You might want to create your own path_processor_outbound service by implementing OutboundPathProcessorInterface.
This implementation may work on /node/{id} paths if the current requests path matches /public/event/** or /pro/event/**.
Analyzing the node entity for it's type (bundle): If it is event generate and return your desired path; if it is not event don't manipulate the path and return the original.

Writing the actual implementation in PHP code may be your own pleasure ;-)

Upvotes: 0

Related Questions