How To Get List Field Values As Labels Instead Of Keys
Published in
1 min readFeb 15, 2018
So you have a regular list text field in your entity and instead of keys, you want to get values. How do you do that? Well as usual in Drupal it will be painful 🤕 but possible 🙌:
Here’s a little function that’ll do it for you:
function getValueAsLabels($entity, $field_name) { // Get allowed values from the field definition.
$allowed_values = $entity->getFieldDefinition($field_name)->getFieldStorageDefinition()->getSetting('allowed_values');
// Go through each value and instead of a key return a label taken from $allowed_values.
return array_map(function($item) use ($allowed_values) {
return ['value' => isset($allowed_values[$item['value']]) ? $allowed_values[$item['value']] : $item['value'] ];
}, $entity->get($field_name)->getValue());
}
A little bit of crunching and you can now get list field labels as easy as:
getValueAsLabels($node, 'field_list');
May the Force be with you.