5

In my module I'm generating some json based on some node content.

$node = node_load($nid);

One of the fields in the node is field_sport_type which is of type List (text). The allowed values look like this:

mens-surfing|Men's Surfing
womens-surfing|Women's Surfing
junior-mens-surfing|Junior Men's Surfing
junior-womens-surfing|Junior Women's Surfing
skate|Skate

When I var_dump($node), the field_sport_type section looks like this:

["field_sport_type"]=>
      array(1) {
        ["und"]=>
        array(1) {
          [0]=>
          array(1) {
            ["value"]=>
            string(14) "womens-surfing"
          }
        }
      }

So, the 'value' is the key from the allowed values, but I want to get the Label, not the key. In other words, I won't want womens-surfing, I want to get Women's Surfing.

How can I get access to the label of my List (text)?

6

You can get the list of values as a keyed array using list_allowed_values, and use it to show the "key" with whatever logic you want.

An example from the API comments section is as follows:

<?php
/*
assuming there's a field named machine name is 'field_my_field_name' whose
type is a list (float, integer or text), and you want to get the values that 
were entered into the "Allowed values list" textarea on the edit screen for the field
*/
$all_fields_on_my_website = field_info_fields();
$allowed_values =       list_allowed_values($all_fields_on_my_website["field_my_field_name"]);
/*
$allowed_values is now an array of $key=>value pairs that
can be dropped into the '#options' value for a form field array, for instance
*/
//example:
$form = array();
$form['my_form_element'] = array(
  '#type' => 'select',
  '#title' => t('Choose something, sucka!'),
  '#description' => t('Descriptive text under form elements rather than above them is a great UX choice, really.'),
  '#options' => $allowed_values,
);
return $form;

Being a "field" in drupal the List field instance attached to a bundle has configuration and settings such as the custom list of items, the default value, whether its mandatory, etc.

5

You can access the key label in a simple way using an Entity Metadata Wrapper:

$wrapper = entity_metadata_wrapper('node', $nid);
$label = $wrapper->field_sport_type->label();

Or using de $node loaded vía node_load():

$wrapper = entity_metadata_wrapper('node', $node);
$label = $wrapper->field_sport_type->label();

You will need the Entity API module, but I think that this module is almost mandatory in custom module coding.

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.