0

In Drupal 7, I have a page content type that has a field called group (so the machine name is field_group). The field is a List (integer) field type.

This field might have allowed values as follows:

0|Description 1
1|Description 2
2|Description 3

If I want to return the key of this field for the current page, the following code correctly works:

field_get_items('node', $node, 'field_group')[0]['value']

If the key were set to 1 for this page, the above code would return 1.

However, is there a way to instead return the associated value (e.g., "Description 1," "Description 2," etc.)?

I thought I had a way to return the value already, but I was told yesterday that my previous method was not a good way to get the value (or key) because my previous method may return extraneous data (such as unwanted HTML), when I really just want the raw key/value itself: How is a field's key (rather than value) obtained?

3 Answers 3

0

As you can see, you pass to field_get_items() the $node parameter. This should tell you that this function will return you a value stored in this Entity. The values of your field are stored in the field itself. You can get your options array as following.

$fieldData = field_info_field('field_group');
$options = $fieldData['settings']['allowed_values'];
3
  • I have verified that this works. In this case, $options appears to be an array that holds the key => value of the requested field.
    – JasonF
    Nov 8, 2017 at 18:17
  • I take back the above comment to some extent. While the code returns all allowed values, I need to return the value for the current page.
    – JasonF
    Nov 8, 2017 at 18:30
  • I think I understand now; you're saying to associate the key with the list in $options. That makes sense.
    – JasonF
    Nov 8, 2017 at 18:37
0

You can also use something like this:

$key = field_get_items('node', $node, 'field_group')[0]['value'];    
$field = field_info_field('field_group');
$allowed_values = list_allowed_values($field);
$value = isset($allowed_values[$key]) ? $allowed_values[$key] : $key;
1
  • This is exactly what I was looking for. It's very easy to understand because you laid out the process in each step until the $value was discovered.
    – JasonF
    Nov 8, 2017 at 18:38
0

You can use field_view_value() for that.

$items = field_get_items('node', $node, 'field_group');
$value = field_view_value('node', $node, 'field_group', $items[0]);

Your Answer

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

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