Let's say you have a field machine name, which might have come from a variety of situations.
$fieldMachineName = 'field_some_field';
You can get the field label from the entity itself, if you have that loaded.
$fieldLabel = $node->get($fieldMachineName)->getFieldDefinition()->getLabel();
Or, you can use the entity_field.manager service to grab the field label from the field definitions.
$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page');
$fieldLabel = $definitions[$fieldMachineName]->getLabel();
This code is really useful when printing validation errors as you'll want to tell the user where the validation error was in terms they understand.
Add new comment