2

I wanted to change some of the forum’s topic's preprocessing. So I copied template_preprocess_forums() into a custom module (myModule), and renamed the function myModule_preprocess_forums().

I get an error that a method cannot be used on a string, $topic. I inspected. When the code is looping through the array $variables['topics'], it expects each array item to be an object. However, in $variables['topics'] there are items that are strings and arrays and no topic objects.

To debug, I inspected $variables['topics'] in the Forums module, but all the items are objects, as expected.

Why would the values passed to myModule_preprocess_forums() differ from what template_preprocess_forums() implemented by the Forums module gets?

3
  • 1
    Assuming I copied this function into it didn't include the function body (or even if it did in some ways actually), I think you're falling victim to an annoying bit of code. I don't know if it's intentional for some reason so I hesitate to say it's a bug, but at the bottom of template_preprocess_forums is: $variables['topics'] = $table;, replacing the var with a render array (the one you're haplessly looping over), and removing the original objects from any scope you have access to in your own preprocess. There might be a way around it but it would be messy
    – Clive
    Commented Mar 6, 2018 at 20:26
  • @Clive you are correct! Thanks. Since this function is a 'hook' and is designed expecting the data to be passed through by reference I want to call this a bug. Changing the markup of that table format is exactly what we wanted to do and cannot as we don't have the original data to loop through. As you said, it would be messy to deconstruct the html table. I will take this to the official issue queue and see what the response is. Thanks again.
    – maestrojed
    Commented Mar 6, 2018 at 21:07
  • FYI, There was an issue in the queue already. I didn't find it on my initial search. drupal.org/project/drupal/issues/2890049
    – maestrojed
    Commented Mar 6, 2018 at 21:47

1 Answer 1

0

It happens because template_preprocess_forums(), which is executed before any hook_preprocess_forums() implementation, overrides $variables['topics'] with the render array for its table.

It would have been better to put the render array in a different array value. As you notice from the function code, starting from Drupal 8.6.x, the original value of $variables['topics'] is available in $variables['topics_original'].

  $variables['topics_original'] = $variables['topics'];
  $variables['topics'] = $table;
  $variables['topics_pager'] = [
    '#type' => 'pager',
  ];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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