Drupal 8 hook_preprocess_node() example

  1. /**
  2.  * Implements hook_preprocess_node().
  3.  */
  4. function custom_module_preprocess_node(&$variables, &$node) {
  5.  
  6. // get node type
  7. $type = $variables['elements']['#node']->getType();
  8.  
  9. // get nid
  10. $nid = $variables['elements']['#node']->id();
  11.  
  12. // Url from node edit route
  13. $url = Url::fromRoute('entity.node.edit_form', ['node' => $nid]);
  14.  
  15. // Link creation
  16. $edit = Link::fromTextAndUrl(t('Edit'), $url);
  17. $edit_link = $edit->toRenderable();
  18.  
  19. // Add class attribute to the link
  20. $edit_link['#attributes'] = ['class' => array('button', 'button-action', 'edit-form-link')];
  21.  
  22. // get current path
  23. $current_path = \Drupal::service('path.current')->getPath();
  24.  
  25. if ($current_path == '/my-companies')
  26. $variables['edit_link'] = $edit_link;
  27. else
  28. $variables['edit_link'] = NULL;
  29.  
  30.  
  31. if ($type == 'profile') {
  32.  
  33. // Get current user
  34. $current_user = \Drupal::currentUser();
  35.  
  36. // Get roles of current user
  37. $roles = $current_user->getRoles();
  38.  
  39.  
  40. if (in_array('administrator', $roles)) {
  41.  
  42. // User has admin role
  43. }
  44. }
  45.  
  46. if ($type == 'my_node_type') {
  47.  
  48.  
  49. // Get field value
  50.  
  51. $field_test = $variables['node']->get('field_test')->getValue();
  52.  
  53.  
  54. // Custom variable for node template
  55.  
  56. $variables['groups_items_list_class'] = 'default';
  57.  
  58.  
  59. }
  60. }