6

I've tried guessing

$node->field_name->fieldDefinition->label
$node->field_name->fieldDefinition->label()

and

$node->field_name->label
$node->field_name->label()

but it did not work.

14

Your first guess was very close, but both are protected properties, so are accessed by getters - functions with the prefix get:

$field_label = $node->field_name->getFieldDefinition()->getLabel();

For reference:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldItemInterface.php/interface/FieldItemInterface/8.2.x

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldDefinitionInterface.php/interface/FieldDefinitionInterface/8.2.x

Edit:

Btw, in twig you don't need the prefix get, because if you tell twig to get something with the name label, it tests all possibilities on the object, first it tries to access the property label, then the method label() and finally the getter getLabel().

{{ node.field_name.fielddefinition.label }}
  • $node->field_name->getfieldDefinition()->label(); also works without the get for the label only. – No Sssweat May 15 '16 at 9:12
  • 2
    That only works because for configurable fields, the field definition is a config entity and has the label() method. FieldDefinitionInterface defines getLabel(), label() would not work on $node->title->getFieldDefinition(). if you use $node->get('field_name'), then you should also get autocomplete of method names if you use an IDE. – Berdir May 15 '16 at 10:38
  • Thanks for the answer. To extend this.. does anyone have any idea of how to set the label in the node? Is there such a thing along the lines of setFieldDefinition? – cwiggo Feb 13 '17 at 15:20
  • @cwiggo, that's no problem, you can set the label in the config of the field. You find it in an exported config in field.field.node.content_type.field_name.yml – 4k4 Feb 13 '17 at 16:18
  • @4k4 but i'm trying to change it depending on a taxonomy term id.. any ideas? – cwiggo Feb 13 '17 at 16:33
2

To get the field label in Twig (in this case in a node-NODETYPE.html.twig):

{{ content.field_FIELDNAME['#title'] }}

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.