Score:0

How to get node information in RouteSubscriberBase::alterRoutes

jp flag

what I'm trying to achieve, is to for some specific nodes set admin theme. I have defined RouteSubscriberBase but how can I get node information here? This code is not working $node = \Drupal::routeMatch()->getParameter('node');

$route->getPath() will return /node/{node}

class RouteSubscriber extends RouteSubscriberBase
{

    /**
     * {@inheritdoc}
     */
    public function alterRoutes(RouteCollection $collection)
    {
        if ($route = $collection->get('entity.node.canonical')) {
            $node = \Drupal::routeMatch()->getParameter('node');
            // dpm($node); - this will be null
            if ($nid == 123) {
                $route->setOption('_node_operation_route', TRUE);
            }
        }
    }

}

Update: As mentioned bellow by @4uk4, RouteSubscriberBase is not right solution for this. As suggested ThemeNegotiatorInterface makes this job. Thank you, @4uk4!

Vikram8888 avatar
in flag
As you said $route->getPath() will return /node/{node} ,by using explode function you can get the node id as a array format ,or try in such way $entity = \Drupal::routeMatch()->getParameter('node'); if ($entity instanceof \Drupal\node\NodeInterface) { // Check if it is a node $nid = $node->id(); // You also have the node object right here }
sonfd avatar
in flag
You'll never be able to get a node ID here - this event will only fire when caches are cleared or when a module is enabled.
4uk4 avatar
cn flag
If you want to choose a different theme for specific nodes you need a custom theme negotiator. See https://drupal.stackexchange.com/questions/281447/themenegotiator-not-working-for-admin-pages
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.