Drupal 10: Getting A Field Label From A Field Name

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

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.