So I am trying to upgrade my modules from Drupal 7 to 8 and some things have been pretty straightforward so far, but I'm stuck at a particular function that I just can't figure out how to implement on Drupal 8. Figuring out exactly how to make these changes on 7 was difficult enough, involving a lot of playing around with print_r. Maybe my approach last time was not the right way and therefore I'm already on the wrong track for Drupal 8. Anyway, I was trying to do a find and replace on node body text to change a pattern into a node URL. The code is below:

 function textreplace_node_view($node, $view_mode, $langcode){
   if($node->type == "article"){
     if(empty($node->content['body'])) return $node;
     $text = $node->content['body'][0]['#markup'];
     $offset = 0;
     $m = array();
     while ( preg_match('/\{\{nodeurl-([0-9]+)\}\}/', $text, $m, PREG_OFFSET_CAPTURE, $offset) ) {
       $offset = $m[0][1] + strlen($m[0][0]);
       $nod = (explode("-", str_replace("{{","",str_replace("}}","",$m[0][0]))));
       $nod = $nod[1];
       $thenode = node_load($nod);
       $text = str_replace($m[0][0], l($thenode->title, 'node/' . $nod), $text);
     $node->content['body'][0]['#markup'] = $text;
     return $node;

I tried looking at how it was implemented in the Book module and the parameters started giving me errors when I changed them to what I saw in the Book module:

function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {

I was getting an error along the lines of $node must be of type EntityInterface...

Any help?

  • 2
    You should use input format for this. – user21641 Dec 4 '15 at 20:41
  • Welcome to Drupal Answers! When you changed your code and got that $node must be of type EntityInterface, was $node still the first agument of the hook? – kiamlaluno Dec 5 '15 at 6:31

This should work, you are changing $build, which you don't need to return:

function textreplace_node_view(&$build, $node, $display, $view_mode) {
  // your code for $text
  $build['body'][0]['#text'] = $text;
  • Hi am using the hook_node_view as function mymodule_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) { How to modify a field when using like this ? any idea ? – KTM Feb 16 '18 at 15:42

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.