2

I am building a module with reactjs and I need to get the current node id from a controller so I can do certain tasks based on the node id but I always receive a null value, my routing is working correctly and my function is the following:

  public function currentNodeId()
    {
        // get current node
        $node_id = \Drupal::routeMatch()->getParameter('node')->Id();

        return new JsonResponse(
            array(
                'node_id' => $node_id
            )
        );
    }

and in mymodule.routing.yml I have:

 mymodule-currentNode:
   path: '/mymodule/currentNodeId'
   defaults:
     _controller: '\Drupal\mymodule\Controller\MyModuleController::currentNodeId'
     _title: 'Current node id'
   requirements:
     _permission: 'access content'

I can get the current node id from my module file 'mymodule.module' doing the same I did in the currentNodeId function:

   $node_id = \Drupal::routeMatch()->getParameter('node')->Id();

Anyone knows if this is some kind of security or am I doing anything wrong? Thank you

EDIT

This is what I have in my js file, I do this call and I want to get the current node id so then I can do a certain task, in the console I get null or undefined every time I do the request

$.get('/mymodule/currentNodeId/', function (data) {
                        console.log(data.node_id);
                    });
  • Are routes allowed to have hyphens? – Kevin Feb 27 '17 at 10:37
  • Yes, at least I get a response of null when trying to do a console.log(node_id) after doing a get request to the controller. – Henrique Alho Feb 27 '17 at 11:46
1

Your route has no node parameter. See the documentation Structure of routes and the example from there:

book.export:
  # This path takes dynamic arguments, which are enclosed in { }.
  path: '/book/export/{type}/{node}'
  defaults:
    # Because this route does not return HTML, use _controller.
    _controller: '\Drupal\book\Controller\BookController::bookExport'
  requirements:
    _permission: 'access printer-friendly version'
    # Ensure user has access to view the node passed in.
    _entity_access: 'node.view'

You can access the route parameters in the controller directly in the function arguments:

public function bookExport($type, NodeInterface $node) {
  // get the id from the controller argument
  $node_id = $node->id();
}

\Drupal::routeMatch()->getParameter() is to get a route parameter outside of the controller, for example in a preprocess hook. For this to work the parameter has to be defined in the current route as well.

  • Hi, thanks for your answer, I'm trying to do what you said but I get an error when calling the get request from my js file because I am not passing the correct parameters like {type} and {node}. $.get('/mymodule/currentNodeId/', function (data) { console.log(data.node_id); }); If I don't know the node id nor the type how can I call the controller? – Henrique Alho Feb 27 '17 at 10:48
  • The path in $.get has to match the path in the route. - Besides from the question, what are you trying to do? To use the node id as route parameter only to get the node id back seems rather pointless, if it is not for demonstration purpose. – 4k4 Feb 27 '17 at 11:01
  • I know that the $.get method has to match the path in the route. What I am trying to do is: I want to get the current node ID from my js function and for that I need to call the controller function with the $.get method and so I can't pass any node id because I don't know the node id. I want to get the node id from the controller so I can do a certain task like make a post and add entry to database based on the current node id. I hope I explained myself. – Henrique Alho Feb 27 '17 at 11:44
  • What do you mean with "current node ID". $.get starts a new request and if you don't tell this request about what node this is you won't find more information in the current route. So the "current node ID" has to come from somewhere else like a user session. – 4k4 Feb 27 '17 at 12:48
  • 1
    Thank you 4k4, I'm really new to Drupal development that's why I was having this kind of problem! I solved it by just setting a session variable every time my module is loaded and then on the controller I get the value from that same variable. Cheers ! – Henrique Alho Feb 27 '17 at 14:08
1

I just wrote a blog article about a dynamic Drupal 8 alternative on https://julian.pustkuchen.com/node/780

Here's my code for a helper function:

<?php
/**
 * Helper function to return the currently loaded entity from the URL (controller).
 * Returns NULL if the currently loaded page is no entity.
 *
 * @return \Drupal\Core\Entity\EntityInterface
 */
function _get_current_controller_entity()
{
  $currentRouteParameters = \Drupal::routeMatch()->getParameters();
  foreach ($currentRouteParameters as $param) {
    if ($param instanceof \Drupal\Core\Entity\EntityInterface) {
      $entity = $param;
      return $entity;
    }
  }
  return NULL;
}
?>

Handle and test with care. We're using it for different types of content entities like nodes, users, commerce_products, ... so far.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.