Drupal - How to access a selected label instead of value

Not sure if there is a better way but I got the value by getting the allowed values first.

$allowed_values = $state->getFieldDefinition('field_state')->getFieldStorageDefinition()->getSetting('allowed_values');
$state_value = $state->get('field_state')->value;
$info['state_name'] = $allowed_values[$state_value];

The proper way is to use options_allowed_values() function. Because the field might not have "allowed_values" setting and options can be provided through the "allowed_values_function".

Live examples:

Case #1: You have an entity object and want to get a label of the value of the field with options.

$field_name = 'field_state';

/** @var \Drupal\Core\Field\FieldStorageDefinitionInterface $field_definition */
$field_definition = $entity->{$field_name}->getFieldDefinition();

// This is a list (array) of options for the field definition:
// [{option1_key} => {option1_value}, {option2_key} => {option2_value}, ...]
$field_allowed_options = options_allowed_values($field_definition, $entity);

// If the field is NOT multiple.
/** @var string|\Drupal\Component\Render\MarkupInterface $field_value_label */
$field_value_label = $field_allowed_options[$entity->{$field_name}->value];

// If the field is multiple.
$field_value = array_column($entity->{$field_name}->getValue(), 'value', 'value');
/** @var string[]|\Drupal\Component\Render\MarkupInterface[] $field_value_labels */
$field_value_labels = array_intersect_key($field_allowed_options, $field_value);

Case #2: You don't have an entity object but you want to get a list of all allowed options of the field of the entity.

$entity_type_id = 'node';
$field_name = 'field_state';

$entity_fields_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions($entity_type_id);

/** @var \Drupal\Core\Field\FieldStorageDefinitionInterface $field_definition */
$field_definition = $entity_fields_definitions[$field_name];
$field_allowed_options = options_allowed_values($field_definition);

Tags:

8