I need the safe output of a key from a select list field within a field collection item.

I'm theming a field collection item and one of the fields is a select list like:


I'm using the following to create some easy to use variables;

$fields = array_keys($content);
foreach ($fields as $field) {
  $field_items = field_get_items('field_collection_item', $content[$field]['#object'], $field);
  $$field = render(field_view_value('field_collection_item', $content[$field]['#object'], $field, $field_items[0]));

This works fine for all fields except for the select list. I need the key of that select list. For this select list field, $field_items is an array which looks like:

array(1) { [0]=> &array(1) { ["value"]=> string(13) "icon-map" } }

However, $field_icon (result of $$field = render(..) ) is Map, which makes sense.

I can get the key by using $field_items[0]['value'] but I'm not sure that's the best way.


I hope this may help

 $key = $form_state['values']['whatever'];
$options = list_allowed_values("field_whatever");
$value = $options[$key];
  • This is right, but it's possible for it not to work (if the allowed values have been altered in the form, list_allowed_values won't bring back the same as what was presented to the user, for example). In that case you could also check $form['whatever']['#options'], assuming you're in a validate/submit handler
    – Clive
    Jun 26 '15 at 14:17
  • else use this method , $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]; Jun 26 '15 at 14:19
  • Same problem with that method @user3783391 - you get the settings for the field, not necessarily what was actually used in the form
    – Clive
    Jun 26 '15 at 14:22
  • 2
    then in that case I suppose wat @Chris Rockwell has given $field_items[0]['value'] is the right choice to get the key. Jun 26 '15 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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