0

In preprocess_node I wrote this and when I do kint($variables['node']) I can see that label is set to "test", however on display it appears with the old label. How can I change the label name? Should it be in preprocess_node or some other hook? Or what else I should update, so it is actually displayed with label replacement?

    $node = &$variables['node'];
    if ($node->getType()=='training') {
      $term = reset($node->get('field_training_type')->referencedEntities());
    }
    if($term instanceof \Drupal\taxonomy\TermInterface && $term->id() == 9) {
      $node->get('field_section_09')->getFieldDefinition()->setLabel('test');
      $variables['node'] = $node;
    }
2

This doesn't work for two reasons. First, you shouldn't change objects unless you want to save the changes because they are shared across the entire Drupal application. Second, preprocess is for preparing variables printed in templates. Changing other variables has no effect.

So in hook_preprocess_node you can change only $variables['content'].

For most fields the label is stored in #title unless the field is built in a special way by callbacks:

$variables['content']['field_bar']['#title'] = 'Foo';

More straightforward, though, would be changing the label directly in hook_preprocess_field:

$variables['label'] = 'Foo';

which is then printed in the template as {{ label }}.


By the way, if you want to rewrite your code for field preprocess you find the node in this variable:

$node = $variables['element']['#object'];

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.