2

We have a custom mymodule that calls mymodule_preprocess_node(&$variables) hook. When we add ksm($variables); to the hook, we are finding the message is printed multiple times (average has been 5x).

How to make mymodule_preprocess_node run only one time?

I am needing to run this hook because I want to check to see if a field is populated with some value then perform some other logic.

Example:

function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
  if(isset($node->get('field_link'))) {
    // perform some logic. 

   ksm('in here'); // printed multiple times. 
  }
}
  • 1
    Is it running five times for each node? – mpdonadio Aug 16 '18 at 18:05
  • @mpdonadio yes, we are noticing ksm('in here') showing up five times. – usernameabc Aug 16 '18 at 18:12
  • 1
    But is $node->nid the same for each? And since you tagged 8, do you have render cache and/or Twig caching disabled? – mpdonadio Aug 16 '18 at 18:56
  • @mpdonadio in our local development environments, we are following Disable Drupal 8 caching during development – usernameabc Aug 16 '18 at 18:58
  • 2
    You're not calling it manually are you? The question reads as if you are. If you are showing more than one node per page, then it will get called for every node being rendered there. Use a debugger to determine if the entity is the same or not. Printing a static string isn't going to tell you a lot. – Kevin Aug 16 '18 at 19:11
2

I found the issue. As @Kevin mentioned, it was being called for every node being rendered. I added a condition to check the view more as well and it is being called just one time now.

function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
  if(isset($node->get('field_link')) && $variables['elements']['#view_mode'] == 'my_view_mode') {
    // perform some logic. 

   ksm('in here'); // printed once as expected 
  }
}

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.