I created a text list field on the user entity. I entered the following for Allowed values list:

apple|A delicious apple
pear|A very delicious pear
orange|A not so delicious orange

I can access the key for the field like this:


which returns apple. But how do I get the text A delicious apple programmatically?

1 Answer 1


Load the field config and look for the key/value pair from the allowed value list?

Much easier though is using the field formatter for this field type OptionsDefaultFormatter:

$build = $user->field_foo->view(['type' => 'list_default']);

What you do with $build depends on the use case. Put it in a render array to be rendered later or

$output = \Drupal::service('renderer')->renderPlain($build);

if you need it now and can't wait until the page is rendered, for example if you want to send an email.

  • Thanks! In my case, I'm using a custom JSONAPI endpoint to return just the rendered value, so I used $build[0]['#markup']. Commented Mar 24, 2021 at 14:19
  • 1
    or render only one field item $user->field_foo->get(0)->view(['type' => 'list_default']);
    – 4uk4
    Commented Mar 24, 2021 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.