Search code examples
drupaldrupal-7drupal-theming

drupal 7: how to access list-field's key instead of its label (field api)


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?


Solution

  • 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];