Pratik Ghela
Pratik Ghela

Reputation: 63

Displaying field collections loop in Content Type TPL file for drupal 7

I have a content type "about" created in Drupal 7. I have a field collection named "field_usf_projects" which is set to unlimited and contains 2 fields, "usf_title" and "usf_description". Now I want to run a for loop which retrieves the field_usf_projects and then displays 2 fields namely ("usf_title" and "usf_description") inside a ul - li structure.

I have gone through many links but cannot find a working solution. Please help me with this.

Thanks in advance.

Upvotes: 0

Views: 689

Answers (3)

Pratik Ghela
Pratik Ghela

Reputation: 63

I was finally fed up with Field collection. I cannot get any data. I have used Multifield which is way too much better than Field collection. Please see it at https://www.drupal.org/project/multifield

Let me know what is better multi field or Field Collection.

Thanks!

Upvotes: 0

Marcelo Vani
Marcelo Vani

Reputation: 56

Here is my solution, on hook_node_view you can use the entity wrapper to get the fields

function mymodule_node_view($node, $view_mode, $langcode) {
  // Check if the node is type 'about'.
  if ($node->type != 'about') {
    return;
  }

  // Get the contents of the node using entity wrapper.
  $node_wrapper = entity_metadata_wrapper('node', $node);

  // Get the contents of the field collection.
  $values = $node_wrapper->field_usf_projects;

  // Loop field_usf_projects.
  foreach ($values as $item) {
    // Print the values of the fields.
    var_dump($item->usf_title->value());
    var_dump($item->usf_description->value());
  }
}

Instead of dumping, you can add the markup for your

  • A nicer thing to do would be use the hook_preprocess_node to add the markup straight into the $variables, and print them via template.

    https://api.drupal.org/api/drupal/modules!node!node.module/function/template_preprocess_node/7

    Upvotes: 3

  • MilanG
    MilanG

    Reputation: 7124

    I can tell you how I'm handling this, event it's a bit dirty and I'm risking to be crucified, but it works for me. If you are inside node template you have $node object. Print it with print_r or similar way and just follow the structure of output to get to your data. It will probably be something like:

    $node->field_usf_title['und']...
    

    If you don't have that $node object find node id and load the node with

    $node = node_load($nid);
    

    first.

    Upvotes: 0

    Related Questions