1

I have a content type "Campus", I would like to concat to the title "Campus name campus". So, there is a hook or something to alter the node getTitle() method in every display?

I've tested:

  • preprocess_node
  • preprocess_page
  • views_pre_build
  • views_pre_render
  • entity_view_alter
  • preprocess_field__title
  • preprocess_page_title

preprocess_field example code:

function usc_theme_preprocess_field(&$variables) {
  if (!empty($variables['element'])) {
    $field = $variables['element'];
    if ($field['#bundle'] === 'campus' && $field['#field_name'] === 'title') {
      /** @var \Drupal\node\Entity\Node $entity */
      $field[0]['#context']['value'] = 'popopo';
      /** @var \Drupal\Core\Field\FieldItemList $list */
      $list = $field['#items'];
      $val  = $list->getValue()[0]['value'];

      $field['#items']      = $list->setValue('testttttt');
      $variables['element'] = $field;

      $entity                          = $variables['element']['#object'];
      $entity->title                   = 'aaa';
      $variables['element']['#object'] = $entity;
    }
  }
}

Thanks all for help.

  • There’s no hook, but you can subclass the node entity class and override the getTitle, label(), etc methods. – Clive Sep 26 at 12:06
  • Can you share your code that you tried – Hodba Khalaf Sep 26 at 12:07
  • Hmm, i'm gonna try to extend node and alter getTitle(), thanks! – Javier Rey Sep 26 at 12:09
  • PD: Editing the question to add the last test i've did. – Javier Rey Sep 26 at 12:09
  • Well, I can't extend Node class, cause my content type exists already... – Javier Rey Sep 26 at 12:35

Your Answer

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

Browse other questions tagged or ask your own question.