1

I defined a formatter for a field with hook_field_formatter_info()/view(). This field is a field collection and renders fine when I choose my custom formatter through the ui.

I can get my (already defined) field collection with:

$field_collection = entity_load('field_collection_item', array($field_nid))[$field_nid];

This returns a FieldCollectionItemEntity. (info) But how can I render this field colleciton programatically.

render($field_collection);

Does not seem to work and I don't see any methods to render this field collection through code even though the ui config has no problem rendering it as I've defined it.

Thanks!

1 Answer 1

2

So it turns out that the field collection 'field' will be treated like a normal field and rendered properly. You don't need to load the field with entity_load. (We don't need any of the fields in the collection, we just want the entire collection). And using field_view_field you can choose your custom formatter:

  //get the nid of the node that contains the field collection from any number of methods
  $node = node_load($nid);
  // the custom formatter was already defined using hook_field_formatter_info() and
  // hook_field_formater_view() (see drupal docs)
  $display = array('type' => 'custom_formatter_name'); 
  //print or 'return' depending if this is a module or a template file
  print drupal_render(field_view_field('node', $node, 'field_name', $display));

The two hurdles for me were (1) finding out that you can add the custom formatter to field_view_field() and (2) that I needed to print out this info (not return) as I was in a template file, not a function of a module (doh!).

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.