2

I'm working on a custom theme and googled the whole day but can't find an answer to my question:

how to print out a cck list field's key instead of its label?

I think it's the right way to access fields via the field api, right? so I try

$output = field_view_field('node', $node, 'field_list');
print render($output);

that seems to be the way to get the label value of the key|label pair. but even if i set the display options format to 'key' - it only prints the label value. what am I doing wrong?

I know there are other options to render the key but how is it possible using field api?

user2275302
  • 23
  • 1
  • 4

2 Answers2

4

You can get the field value itself (which will be the allowed values array key) with field_get_items():

$items = field_get_items('node', $node, 'field_list');
$key = $items[0]['value'];

If you need to match those up again at any point you can get the full key/value list from the field metadata:

$info = field_info_field('field_list');
$values = $info['settings']['allowed_values'];
$label = $values[$key];
Clive
  • 36,918
  • 8
  • 87
  • 113
2

Here's a similar way. This example works for a Country list with ISO codes. The idea is to render the Name of the Country that was selected because the dump returns only the key ( iso code in this case)

Format of the select list on the backend:

AR|Argentina
US|United States

Assuming you have selected United States on the backend and you want to print the country name on the node template:

$country_field = field_info_field('field_country_iso');
$country_iso = $node->field_country_iso[LANGUAGE_NONE][0]['value'];
$country_name = $country_field['settings']['allowed_values'][$country_iso];

then

print $country_name; // This will return United States, not US code

I hope this helps.