Preprocess field_collections and override output

Public

Field Collections are hard to preprocess. I've been down the path of trying to preprocess them for a template and got lost in an array or two. Heres a handy snippet to help you override the render element of your field collection.

</> CopyGet raw version
php
  1. function mytheme_preprocess_field(&$vars) {
  2. if($vars['element']['#field_name'] == "field_your_fc_field"){
  3. $fcs = array();
  4. foreach (element_children($vars['element']) as $key) {
  5. $fcs[] = array_pop($vars['element'][$key]['entity']['field_collection_item']);
  6. }
  7. // now you have all your fcs pulled out of that nasty array
  8. foreach ($fcs as $fc) {
  9. # code... that
  10. }
  11.  
  12. // I would recommend overrideing items markup for whatever black magic you desire
  13. $vars['items'] = array(
  14. '#markup' => "Whatever you need to render",
  15. );
  16. }
  17. }
  18.  

Comments

Oleg Videnov's picture

Cool stuff !

Norman's picture

That helped a lot!