1

I have a custom field field_sold which contains a single boolean value. I'm trying to use the following function to retrieve the content of the field, but it always seems to return null:

function <theme>_render_field($node, $field_name, $delta = 0, $display = array()) {
   $field = field_get_items('node', $node, $field_name);
   $field = field_view_value('node', $node, $field_name, $field[$delta], $display);
   return render($field);  
}

When trying to dumping the $field variable between the calls to field_get_items() and field_view_value() I recieve the following output:

// after field_get_items()
Array ( [0] => 
   Array ( [value] => 1 ) ) 
// after field_view_value()
Array ( [#markup] => [#access] => 1 ) 

When I'm using the above function for other fields it works as expected, for instance when rendering a image field like this:

print <theme>_render_field($node, 'field_image', 0, 
                     array('type' => 'image', 
                           'settings' => array(
                           'image_style' => 'object_200x300',
                           'image_link' => 'content')
                           ));
7
  • Are you sure you're actually rendering it and haven't forgotten to echo?
    – Clive
    Feb 17, 2014 at 9:47
  • @Clive - Yes, I'm very sure. I event tried to cast it to an int before printing like: print intval(<theme>_render_field($node, 'field_sold')); Feb 17, 2014 at 9:48
  • @Clive - I updated my question. Feb 17, 2014 at 9:59
  • At a guess, the $display settings your passing in for the bool field are off somewhere - what are you passing for that?
    – Clive
    Feb 17, 2014 at 10:22
  • @Clive - I'm using the default value for the display argument: print <theme>_render_field($node, 'field_sold'); Feb 17, 2014 at 10:59

1 Answer 1

1

Set

$display['type'] = 'list_key';

in your theme function to get not null key of field. Or create own formatter, for ex.

function mymodule_field_formatter_info() {
  return array(
      'my_formatter' => array(
          'label' => t('My formatter'),
          'field types' => array('list_boolean'),
      ),
  );
}


function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  switch ($display['type']) {
    case 'my_formatter':
      foreach($items as $delta => $item) {
        $value = $item['value'] == 1 ? '<span class="">ON TEXT</span>' : '<span class="">OFF TEXT</span>';
        $element[$delta] = array(
            '#markup' => $value,
        );
      }
      break;
  }

  return $element;
}

and after that set

$display['type'] = 'my_formatter';

in Your theme function

Your Answer

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

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