There are some good resources on how to theme CCK3 multigroup for Drupal 6. However, there doesn't seem to be that much information for Field Collection.

You can use the following to print out your field collection in your node.tpl.php file:

 print render($content['your_field_collection']); 

But how do you get to the fields contained within the collection? This discussion recommends using a field_collection_item.tpl.php file. However, that isn't much use if you want to wrap the field elements in a custom DIV.
For example, lets say I had a field collection called 'Block' with a text field and an image field and I wanted to wrap the text & image field in a custom DIV. How would I do that?

Also what happens if you want to theme field collections that are stored within a parent field collection?

This thread gives an example, but it incorporates Drupal's link system and so is quite complex to follow. Does anyone have any simpler field collection theming examples?

Thanks!

Comments

RobW’s picture

Here's some quick pointers:

If we have something like

Field Collection Field
-Field Collection Item #1
-Collected Field 1
-Collected Field 2
-Collected Field 3
-Field Collection Item #2
-Collected Field 1
-Collected Field 2
-Collected Field 3

To theme "Field Collection Field", which contains all the field collection items, you can use field--your-field-collection-name.tpl.php, just as you would any other Drupal field. You will run into two problems though:

  1. field--your-field-collection-name.tpl.php will cascade and theme all of your collected fields, in this example Collected Field 1, Collected Field 2, etc. See #1137024: Field--your-field-collection.tpl.php cascades and overrides all collected field's tpls.
  2. Field collection module adds a prefix and suffix which contain its own wrapper divs, the add/edit links, and other information you can modify under the Display Fields tab of your content type.

To completely remove the wrapping tags you could use the very dirty

  unset($content['your_field_collection']['#prefix']);
  unset($content['your_field_collection']['#suffix']);

in your content type tpl, and add wrapping code there. Of course you will lose both the wrappers, the add/edit links, and any other functionality added there by Field Collections module. You could also use the entity_load() with foreach statement described in #1107214: Field Collection tpl overrides and accessing field collection field values from node.tpl, but I think that's also a slightly dirty solution involving loading functions when you would prefer to be using theme files. The current best option would be to override the prefix and suffix by altering field_collection_field_formatter_view() and theme_field_collection_view(), which create prefix and suffix, in your template.php, or writing a preprocess function. I have no code samples for that because... well I haven't gotten around to playing with it.

In the future I'd like to see a field-collection.tpl.php that we can alter on a per field collection basis, but that's not available right now.

Theming Field Collection Item #X is much easier. To override them sitewide, use field-collection-item.tpl.php, or check #1100736: Template filename should use dashes not underscores for a per-collection patch.

And to theme Collected Field X, you can use Drupal 7's built in field--your-field.tpl.php.

Theming collections within collections should work pretty much the same. The example I wrote out with entity_load() and foreach statements might have been a little complex - a simplified generic version would be

// check if field collection is not empty. If content exists, do some stuff.
if (!empty($content['your_field_collection'])) {

  //Your custom wrapper goes here
  print '<div class="collectin-it">';

  //Grab each entity uri (which is basically a field collection item), and load it through entity_load(). The entity type is field_collection_item.
  foreach ($content['your_field_collection']['#items'] as $entity_uri) {
    $a_field_collection_item = entity_load('field_collection_item', $entity_uri);

        //Now you have a variable with the entity object loaded in it, and you can do stuff. 
    foreach ($a_field_collection_item as $a_field_collection_item_object ) {
     print render($a_field_collection_item_object->field_1);
     print render($a_field_collection_item_object->field_2);
     print render($a_field_collection_item_object->field_3);
    }

  }

  //close your custom wrapper.
  print '</div>' . "\n"; 
}

Hope that makes it easier to understand. I edited the original issue solution as well.

[Edited for typos on 6/8/11]

big_smile’s picture

Thanks! The code you posted is a huge help and makes everything clearer.

Just to double check: Are the double dollar signs in print render($$a_field_collection_item_object->field_1); a mistake?

Also, do you have any pointers you could give on using the code you posted to access fields that are stored in field collections that are children of other field collections. (i.e. accessing field collections that are inside field collections)

I have tried lots of variations of the code you posted to do this, but nothing seems to work.

Thanks!

RobW’s picture

Double $ signs were a total mistake. Edited them for future readers (is editing so much ok? I hope so).

I would think you'd need to do another entity load, as field collections inside field collections are probably another entity reference in the field collection entity. Try using the dsm() function provided by the Devel module on your nested collection's field -- something like dsm($a_field_collection_item_object->your_nested_collection); -- to see where your nested field collection's uri can be found, then use an entity_load(). Good luck.

big_smile’s picture

Thanks for your help.

Using dsm($a_field_collection_item_object->your_nested_collection); only shows array containing a UND with some more numbered arrays.

However, using dsm($node); shows that the children field collections follow the exact same 'ordering' as the parent field collections.
Therefore, the following code should work (in theory):

<?php
  // check if field collection is not empty. If content exists, do some stuff.
  if (!empty($content['field_parent_collection'])) {
      //Your custom wrapper goes here
      print '<div class="collectin-it">';
      
      //Grab each entity uri of Parent Collection
      foreach ($content['field_parent_collection']['#items'] as $entity_uri) {
          $a_field_collection_entity = entity_load('field_collection_item', $entity_uri);
          
          //Now you have a variable with the entity object loaded in it for the parents, and you can do stuff. 
          foreach ($a_field_collection_entity as $a_field_collection_item_object) {
              //Grab each entity uri of Child Collection
              foreach ($a_field_collection_item_object['field_child_collection']['#items'] as $entity_uri) {
                  $a_field_collection_entity = entity_load('field_collection_item', $entity_uri);
                  
                  //Now you have a variable with the entity object loaded in it for the children, and you can do stuff. 
                  foreach ($a_field_collection_entity as $a_field_collection_item_object) {
                      print render($a_field_collection_item_object->field_1['und'][0]['value']);
                      print render($a_field_collection_item_object->field_2['und'][0]['value']);
                  }
              }
          }
      }
      
      //close your custom wrapper.
      print '</div>' . "\n";
  }
?>

However, it doesn't produce anything. Does anyone have an ideas or pointers?

RobW’s picture

My initial thoughts are somewhere in the numbered arrays you get from dsm($a_field_collection_item_object->your_nested_collection) is the entity uri.

The way that field collections work might help you figure this out. Field collection fields aren't really in the node itself; rather each instance of a field collection is a completely separate entity with some fields on it (like a super simplified mini node), and those entities are connected to the node through a reference that contains a field entity uri. It's like how you work with node reference fields, if:

node reference field == field collection
nid == field collection entity uri
node_load() == entity_load()

So what you're looking for is the an integer at the end of an array that represents your desired field collection entity, and then load an array filled with the entity object through entity_load(), and then drill down in that for your content.

big_smile’s picture

Thanks for your continued help.

Do you (Or anyone else) know of any tutorials that explain how to extract arrays and loading them with entity_load?
It sounds quite simple, but after playing around with it for a couple of hours, I think it's just a bit above my skill level!!

RobW’s picture

Any time you're dealing with a Drupal function, the best place to start is the Drupal API reference: http://api.drupal.org/api/drupal. It will give you the parameters the function takes, along with various levels of explanation depending on the people who wrote the docs. There are often comments at the bottom that highlight specific problems and caveats.

Information on entity_load() is here: http://api.drupal.org/api/drupal/includes--common.inc/function/entity_lo...

One thing that's kind of a pain with entity_load() is it returns an array, containing an object keyed as the entity uri, containing an array containing the actual field information. That's why I have the extra foreach up there, to get past the ever-changing entity uri that is the object key.

Of course all of this requires a little bit of php familiarity. I am a relative novice too, so there may be better ways to do some of these tasks.

WilliamB’s picture

Hello and thanks for the pointer.
However after applying the patch and succesfuly theming a collection, i still can't theme a field within a collection.
You wrote And to theme Collected Field X, you can use Drupal 7's built in your-field--field.tpl.php.

But for me it always was field--field_your_field_name.tpl.php. Out of the field collection field work fine with their respective template but i can't find how to set a template for the field within the collection.

My fist field inside the collection is field_chap_picto.
I've tried field field--field_chap_pic.tpl.php, field--field-chap-pic.tpl.php, field_chap_pic--field.tpl.php and field-chap-pic--field.tpl.php.

I would be grateful if you could help me there.

Thanks in advance.

Edit: actualy i noticed that both the collection field and the field inside it are themed by the same template.
Let say my collection field is called field_col_test.
When i edit field--field_col_test it ll affect both the collection and every single field inside it...
What i am looking to do is apply different template to the collectionfield and the field isnide it...

At moment i'm just using a switch case on $element['#field_name'] and it works but i would like to find out why i cant theme indivudal field.

RobW’s picture

your-field--field.tpl.php was a typo, you are correct that the theme override is field--your-field.tpl.php.

If you create a field--your-field-collection.tpl, it will apply to all of the fields inside of your collection -- this is a bug that hasn't been addressed yet. But if you have no field--your-field-collection.tpl, and you use print render() inside your field-collection-item tpl, I believe you can use specific, field--your-field templates for your collected fields. At least it's working for me.

It seems the two ways to get around any ambiguity is by entity_load() directly in the node.tpl, or by printing values or markup from $element or $item in the field-collection-item.tpl, as you are currently doing.

tchopshop’s picture

This might be a views templating issue, but I'm having trouble removing the wrapper div from a field collection view. The markup I want to remove is:

<div class="field-collection-view clearfix field-collection-view-final">

I've tried every view template -- and I was able to remove the other wrappers from all other fields using views templates and style options. But this is a stubborn wrapper.

I tried the suggestion in #1 to unset the wrapper in a quick and dirty way by putting that code in a node--my-content-type.tpl.php but that didn't work either, perhaps I didn't do it the right way.

Any suggestions?

RobW’s picture

Looks like Drupal.org filtered out your code example -- could you wrap it in <code> tags so we can see it?

lukus’s picture

I have a field collection which includes two text fields. The field collection is repeatable an infinite number of times.

I wanted to have all the mark-up available in two arrays, so I could have as much flexibility as possible when rendering my node using a (.tpl.php) template file.

I've found the following works well for me. Including it here in case it helps anyone else.

<?php
$field1=array();
$field2=array();

$item_count=0;

if(!empty($content['field_YOUR_FC_LABEL']['#items'])) 
foreach($content['field_YOUR_FC_LABEL']['#items'] as $item) {

        // because field items are numbered consecutively, the correct index needs to be retrieved here
        $index=$item['value'];  

        // replace 'field_field1' with your field name
        $field1[]=$content['field_YOUR_FC_LABEL'][$item_count]['entity']['field_collection_item'][$index]['field_field1'][0]['#markup'];

        // replace 'field_field2' with your field name
        $field2[]=$content['field_YOUR_FC_LABEL'][$item_count]['entity']['field_collection_item'][$index]['field_field2'][0]['#markup'];

        $item_count++;
 }
?>

This fills two arrays .. $field1, and $field2 which can be inserted into a template file wherever they're needed.

tim.plunkett’s picture

Status: Active » Fixed

For #10, please see http://drupal.org/node/1249894. I agree that the addition of clearfix is heavyhanded, there is no easy way to get around it without hacking the module.

See http://drupalcode.org/project/field_collection.git/blob/refs/heads/7.x-1... for the relevant code.

Otherwise, I consider this issue fixed.

Cray Flatline’s picture

I have a field collection field_recipe_steps with two fields field_recipe_steps_image and field_recipe_steps_description.
I tried example with entity_load(), and print_r() shows me that everything is loaded correctly (seems to :)), but

print render($a_field_collection_item_object->field_recipe_steps_image);
print render($a_field_collection_item_object->field_recipe_steps_description);

doesn't output anything even though print_r($a_field_collection_item_object->field_recipe_steps_image) contains information about image.

Please help me find a correct way to render it. Thanks in advance!

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

topdawg’s picture

This may be too basic a question but can you explain how to interpret the following into my situation?
in your code-
'field_YOUR_FC_LABEL' - 'field_collection_item' - 'field_field1'
in my field collection, the following:

'my_field_collection' - 'field_collection_item'

what is the last 'field_field1' ?
by YOUR_FC_LABEL I am assuming it is 'my_field_collection' prefixed as 'field_my_field_collection'

lukus’s picture

@topdawg;

In my example I'm retrieving a set of two fields that are defined in a field collection with the machine-name 'field_YOUR_FC_LABEL'.

You need to change this to match the field name that you're using to contain your field collection reference.

field_collection_item is a standard part of the data structure that field_collection module makes available. You don't need to change this.

field_field1 and field_field2 are totally dependent on the fields that you've defined within your referenced field collection. You need to alter these references to match the fields you've defined in via the field collection admin interface.

Hope this helps.

topdawg’s picture

The way I style is as follows, after of course determining what print_r loads in the node. dsm(print_r($variables);
<div class="my-class-for-label">Description - <span class="my-class-for-field"><?php print render($content['field_collection_item_object']['#items'][0]['value']); ?></span></div>

kovalsky’s picture

Hi,
It's probably a stupid question, but I don't understand, how you fill the $content, can someone explain me this point? (I'v probably miss something, but this doesn't works for me and I really need to theme my field collection).

Blue’s picture

Anonymous’s picture

Thanks lukus for #12.

This worked perfectly for me when placing it in a "node.tpl.php" override and having the content dump into the appropriate HTML elements structure by JQueryUI Tabs.

Example

print '<div id="tabs"><ul>';
//To start the Anchor tags at "1" IE "#tabs-1" 
$item_count=1;
foreach ($field1 as &$value) {
    print '<li><a href="#tabs-' . $item_count . '">'  . $value . '</a></li>';
    $item_count++;
}
print '</ul>';

//To start the Anchor tags at "1" IE "#tabs-1" 
$item_count=1;

foreach ($field2 as &$value) {
	print '<div id="tabs-' . $item_count . '">'  . $value . '</div>';
    $item_count++;
}

print '</div><!-- /#tabs --> ';
Zahak’s picture

Have been working a bit with field collection, and manage to get the job done, but not really happy. There have to be a better way of doing this?

<?php foreach($content['field_ingredients']['#items'] as $entity_uri) :
      $field_collection_item = entity_load('field_collection_item', $entity_uri);
      foreach($field_collection_item as $field_collection_object) : ?>
        <div class="amount">
          <?php print $field_collection_object->field_ingredient_volume['und'][0]['value']['name']; ?>
          <?php print $field_collection_object->field_ingredient_unit['und'][0]['taxonomy_term']->name; ?>
        </div>
        <div class="ingredient">
          <?php print $field_collection_object->field_ingredient_name['und'][0]['taxonomy_term']->name; ?>
        </div>
    <?php endforeach; endforeach; ?>

* Short description. Wrapping fields from a field collection, where field 1 and 2 are wrapped together, and field 3 is wrapped separately.

Ps. I'm really new to Drupal, so happy for any tip!

Neltharian’s picture

Version: 7.x-1.0-beta1 » 7.x-1.0-beta4
Status: Closed (fixed) » Needs review

Hi to all! I've had the same problem - i have field collection with 4 text fields, which i need print seperatly. I've tried solutions printed in this thread but i didn't found them usefull, exept #22 but for ex. <?php print $field_collection_object->field_ingredient_volume['und'][0]['value']['name']; ?> print all values in field.

So I found another solution. You need Devel module instaled. When you view a node with field collection you want to theme go to "Devel" tab. There you will find 3 tab - Load, Token and Render. You need last one.

There you will see field_collectionname - go to this.

As final (in my case) I received a code:

<?php print render($content['field_contpass'][0]['entity']['field_collection_item'][1]['field_cname'][0]['#markup']);?>

As follows, I printed value from field_cname that located in first field collection.

Hope this will help.

tim.plunkett’s picture

Status: Needs review » Closed (fixed)

Thanks for the added info, but this issue has been closed.

simon.fryer’s picture

Sorry to post in here, but it's the most relevant thread i've found.

I refuse to believe that to theme a field collection

- Which i class as a collection of fields to aid formatting, for example (div, h1, image, link - repeat)

I need to do this in node.tpl.php;

print $field_collection_object->field_ingredient_volume['und'][0]['value']['name'];

Or similary in field--COLLECTION_NAME.tpl.php;

$array[1]['entity']['field_collection_item'][1]['field_title']['#object']['field']

To get to an individual field?

Now, i can't imagine that the module would of made such a massive over sight and google is still not helping 3 hours on after playing with various file names and functions - so how does one properly style a field collection that doesn't involve traversing a 7 dimension array?

Zahak’s picture

Depending on what you want to do, field group may be a better module.

http://drupal.org/project/field_group

MickL’s picture

to print a certain field of a field collection in a node.tpl.php do:

<?php
$wrapper = entity_metadata_wrapper('node', $node);
foreach ($wrapper->field_fieldcollectionname as $i): ?>
  <?php  print $i->field_myfield->value(); ?>
<?php endforeach; ?>
?>
rgchi’s picture

Is there any reason why not to use Field Collection Views?

kevishie’s picture

You should be able to do entity--bundle.tpl.php

Works for me.

Example field-collection-item--field-name.tpl.php

adamelleston’s picture

What @kevishie says in #29 is the same as how I theme field collections.

If you want to theme fields in field collections I do the follow (based on a field collection called "field_statistics" with a field in it called "field_statistics_context")

field-collection-item--field-statistics.tpl.php
field--field_statistics_context--field_statistics.tpl.php

So theming the field in a field collection is field--field_name--field_collection_name.tpl.php

creando sensaciones’s picture

Analizing the content object I just managed to render single field collection items in node.tpl.php that way:
Single value field:

$field_collection_item = current($content['field_my_collection'][0]['entity']['field_collection_item']);
    print render($field_collection_item['field_my_field_1']);
    print render($field_collection_item['field_my_field_2']);

Multi value field:

foreach($content['field_my_collection'][0]['entity']['field_collection_item'] as $field_collection_item)  {
    print render($field_collection_item['field_my_field_1']);
    print render($field_collection_item['field_my_field_2']);
    }
head’s picture

Version: 7.x-1.0-beta4 » 7.x-1.x-dev
Component: Miscellaneous » Documentation

Write the full instructions.
Spend a lot of time searching for information.
I tried to use:

foreach($content['field_my_collection'][0]['entity']['field_collection_item'] as $field_collection_item)  {
    print render($field_collection_item['field_my_field_1']);
    print render($field_collection_item['field_my_field_2']);
    }

but multi-fields are not displayed.

To get all the multi field I need to check the array.
The record will look like this:

foreach($content['field_my_collection'][0]['entity']['field_collection_item'] as $field_collection_item)  {
    print render($field_collection_item['field_my_field_1']);
    print render($field_collection_item['field_my_field_2']);
    }
foreach($content['field_my_collection'][1]['entity']['field_collection_item'] as $field_collection_item)  {
    print render($field_collection_item['field_my_field_1']);
    print render($field_collection_item['field_my_field_2']);
    }
foreach($content['field_my_collection'][2]['entity']['field_collection_item'] as $field_collection_item)  {
    print render($field_collection_item['field_my_field_1']);
    print render($field_collection_item['field_my_field_2']);
    }
foreach($content['field_my_collection'][3]['entity']['field_collection_item'] as $field_collection_item)  {
    print render($field_collection_item['field_my_field_1']);
    print render($field_collection_item['field_my_field_2']);
    }

Tell me how to do it correctly.

translate.google

hoff331’s picture

I need help with this too. This solution does not iterate through multiple field collections.

I have a node that has "Items for Sale" field collections (FC) attached.

Each "Item for Sale" FC has the following fields:
"Item for Sale Name"
"Item for Sale Price"
"Item for Sale Description"
"Item for Sale Image"
(actual field names are as expected, ex. "field_item_for_sale_image")

I am trying to spit out the fields in the following HTML:

<div class="listing">
   <div class="listingLeft">
      'item_for_sale_image'
   </div>
   <div class="listingRight">
      <h3>'item_for_sale_title'</h3>
      'item_for_sale_price'
      'item_for_sale_description'
   </div>
   <div class="clearfix"></div>
</div>

I have the following php:

<?php
		// check if field collection is not empty. If content exists, do some stuff.
		if (!empty($content['field_item_for_sale'])) {

			//Title of content
			print '<h2>Featured Items for Sale</h2>';
			//Your custom wrapper goes here
			print '<div class="listing">';
			
			$item_count=0;
	
			foreach($content['field_item_for_sale'][$item_count]['entity']['field_collection_item'] as $field_collection_item)  {
				print '<div class="listingLeft">';
				print render($field_collection_item['field_item_for_sale_image']);
				print '</div>';
				print '<div class="listingRight">';
				print '<h3>' . render($field_collection_item['field_item_for_sale_title']) . '</h3>';
				print render($field_collection_item['field_item_for_sale_price']);
				print render($field_collection_item['field_item_for_sale_description']);
				print '</div>' . "\n";
				print '<div class="clearfix"></div>';
				
				$item_count++;
			}
	
			//close your custom wrapper.
			print '</div>' . "\n"; 
		}
		?>

Unfortunately, I have no idea how to loop through the multiple field collections.

kevinquillen’s picture

How do you simply call the view() of a FieldCollectionItemEntity as if it were about to be rendered to the page? I am trying to create a precaching method that loads field collections for custom entities via drush and renders them, which creates a static HTML cache of them in the database... I tried:

public function preCacheFieldCollectionTables() {
    $items = db_query('SELECT item_id FROM {field_collection_item} WHERE field_name = :field ORDER BY item_id DESC', array(':field' => 'field_property_booking'))->fetchAllAssoc('item_id');
    foreach ($items as $item_id => $value) {
      $collection = field_collection_item_load($item_id);
      entity_view('field_collection_item', array($collection), 'full');
    }
  }

But this throws a fatal error:

Argument 1 passed to entity_key_array_by_property() must be an array, object given

kevinquillen’s picture

got it


public function preCacheRateTables() {
    $items = db_query('SELECT property_id FROM {isilink_property}')->fetchAllAssoc('property_id');
    foreach ($items as $item_id => $value) {
      $entity = isilink_property_load($item_id);

      if (count($entity->field_property_booking[LANGUAGE_NONE]) > 0) {
        watchdog('isilink', 'Priming rate table cache for property_id @property_id', array('@property_id' => $entity->property_id));
        $desktop = entity_get_controller('isilink_property')->buildContent($entity, 'full');
        $mobile = entity_get_controller('isilink_property')->buildContent($entity, 'mobile');
        $html = render($desktop['field_property_booking']);
        $html = render($mobile['field_property_booking']);
      }
    }
  }

spencerthayer’s picture

    if (!empty($content['field_articles'])) {
        $item_count=0;
        foreach($content['field_articles'][$item_count]['entity']['field_collection_item'] as $field_collection_item)  {
            print '<div class="articlesPad">';
            print '<h3><a href="' . render($field_collection_item['field_url']) . '" target="_blank">' . render($field_collection_item['field_title']) . '</a></h3>';
            print render($field_collection_item['field_subhead']);
            print '</div>';
            $item_count++;
        }
        print "\n"; 
    }
hoff331’s picture

@spencerthayer
Does this loop through each of your field collections? If so, what is the difference between your code and #33?

kevinquillen’s picture

If you are referring to mine, yes. I had to load the host entity and loop and build the content. I wish there were a faster way. But that is somewhat niche.

Why are you guys doing this manually and not using View Modes on each Field Collection? Seems like an easier approach. You can add arbitrary container divs with the Fieldgroup module inside a VIew Mode display to get your divs, and use something like the Fences module to wrap one like 'title' with an h3.

head’s picture

StatusFileSize
new1.03 KB
new949 bytes

Two levels.

1
1

2
2

How to get a field from the second level?
3

How to set the name of the function by using preprocess for my case?

Read http://drupal.org/node/1137024 and still does not work.

I would like to see a working example.

thanks

head’s picture

head’s picture

StatusFileSize
new2.43 KB
hoff331’s picture

@kevinquillen

How would you implement a hook_theme_preprocess in order to style the field collection entities?

markabur’s picture

#31 was helpful, thanks.

jeffglenn’s picture

Not sure if this would help anyone out but I wanted to post it just in case.

The main thing I wanted to do was to change the 'Prefix' and 'Suffix' Field Collections spit out. Instead of having a 'div' with field_collection classes, I wanted to create an unordered list. I tried a few different things in the template.php file, and since I don't really know my way around, they didn't work.

Here is my solution:

  • In the Content Type I changed the 'Display Format' to 'Fields Only'. That removed the <div class="field-collection-container"> & <div class="field-collection-view"> and I was left with only the fields.
  • Then in my 'field-collection-item--content_type.tpl' I broke out all of my fields using the <?php print render($content['field_name']); ?> etc. and then wrapped everything within an <li>.
  • In my node--content_type.tpl I hid my Field Collection using hide($content['field_collection_name']); then printed the rest of my content and printed the Field Collection afterward wrapped in a <ul>.

This may have been obvious to some and may not be what most need but it worked for me and now I have a clean <ul><li></li></ul> structure.

RobW’s picture

@jeffglenn: To better handle the prefix/suffix problems, check out #1157794: Move markup to template files and improve theming in new 2.x branch.

jeffglenn’s picture

@RobW: Very nice! Glad to see this is getting worked on. I'll jump over there and see if I can help.

jack-pl’s picture

Theming multiple field collection with template file

For example:

Field collection name: boxes
Template file: field--field-boxes.tpl.php

Each collection contain:

  • image
  • header
  • link
  • content

First I need to build an array with all field collecion items and put this array into my custom field template file (field--field-boxes.tpl.php).

template.php

/**
 * Override or insert variables into field templates.
 */
function YOUR_THEME_preprocess_field(&$variables) {

  if ($element['#field_name'] == 'field_boxes') {
    $items = $variables['items'];

    // create an array for field collection items
    $boxes = array();

    // find items and push them to their arrays
    foreach ($items as $fields) {

      foreach ($fields['entity']['field_collection_item'] as $elements){
	
        // image ( In this example I need only url )
        if (isset($elements['field_image'])) { 
          $img = $elements['field_image'];
          $uri = $img['#object']->field_image['und'][0]['uri'];

          // get full url to the image
          $field_image_url = file_create_url($uri);
        }
        else {
          $field_image_url = '';
        }

        $field_link = isset($elements['field_link']['#object']->field_link['und'][0]['value']) ? 
          $elements['field_link']['#object']->field_link['und'][0]['value'] :
          '';

        $field_header = isset($elements['field_header']['#object']->field_header['und'][0]['value']) ? 
          $elements['field_header']['#object']->field_header['und'][0]['value'] :
          '';

        $field_content = isset($elements['field_content']['#object']->field_content['und'][0]['value']) ? 
          $elements['field_content']['#object']->field_content['und'][0]['value'] :
          '';
	
        // box items					
        $box = array(
          'img_url' => $field_image_url,
          'header' => $field_header,
          'content' => $field_content,
          'link' => $field_link
        );
						
        // array with all boxes
        $boxes[] = $box;
      }
    }
    // add a new variable to template file.
    $variables['boxes'] = $boxes;
  }
}



field--field-boxes.tpl.php

Use this file for theming. All your field collection items are now in $boxes variable, which is an array of results.

Let's say the field collection contain three boxes, so our new added variable will look as follows:

Array
(
    [0] => Array
        (
            [img_url]	=> full-path-to-image/image1.jpg
            [header]	=> HEADER #1
            [content]	=> FIRST BOX CONTENT...
            [link]	=> LINK EXAMPLE #1
        )

    [1] => Array
        (
            [img_url]	=> full-path-to-image/image2.jpg
            [header]	=> HEADER #2
            [content]	=> SECOND BOX CONTENT...
            [link]	=> LINK EXAMPLE #2
        )

    [2] => Array
        (
            [img_url]	=> full-path-to-image/image3.jpg
            [header]	=> HEADER #3
            [content]	=> THIRD BOX CONTENT...
            [link]	=> LINK EXAMPLE #3
        )

)

and you can print all these results using the foreach loop

<?php foreach ($boxes as $delta => $box) : ?>
  <div class="box">
    <div class="box-header"><?php print $box['header']; ?></div>
    <div class="box-img-url"><?php print $box['img_url']; ?></div>
    <div class="box-content"><?php print $box['content']; ?></div>
    <div class="box-link"><?php print $box['link']; ?></div>
  </div>
<?php endforeach; ?>
J0keR’s picture

1. Count the field_collection_item
$page_counter = count($node->field_collection_item['und']);
2. Do the for loop limit in count item .
for($item_count=0;$item_count<$page_counter;$item_count++){
Your code here

pinder’s picture

Anyone have any luck using field_view_field() instead of ['und'][0]['value']?

Trias2013’s picture

none of the above worked for me, here is my code:

render values of a field collection in a content type:

<?php if (!empty($content['field_collection'])) :
    for($i=0;!empty($content['field_collection'][$i]);$i++) : ?>
        <?php $field_collection_item = current($content['field_collection'][$i]['entity']['field_collection_item']); ?>
        <h2><?php print render($field_collection_item['field_title']); ?></h2>
        <div>
            <?php print render($field_collection_item['field_image']); ?>
            <?php print render($field_collection_item['field_description']); ?>
        </div>
    <?php endfor; ?>
<?php endif; ?>

Please provide reliable .tpl files for theming, so custom code like this isn't necessary.

jack-pl’s picture

@pinder You can grab raw values from your collection field in that way:

foreach ($items as $k){

	foreach ($k['entity']['field_collection_item'] as $id => $field_collection){
	
		$field_collection_item = field_collection_item_load($id);
		$item_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);
		
		$field_title		= $item_wrapper->field_title->value(); 			// title
		$field_image		= $item_wrapper->field_image->value(); 			// an array with image data
		$field_image_uri	= $field_image['uri'];							// image URI
		$field_description	= $item_wrapper->field_description->value(); 	// description

	}
	
}

* in this example all txt fields within field collection should be stored as a plain text, even if they are in html format, otherwise $item_wrapper->field_example->value() will return array


@Trias2013 This should work if you are using proper template file
For example:
If your field collection has a name "field_image_boxes" then your field template file should be: "field--field-image-boxes.tpl.php". This is the way of theming the field with field template file, not field collection template file.

danny englander’s picture

Did you have a look at this issue and comment, it provides some insight to the templating system. For example, I have a field collection called Video Collection with a machine name of field_video_collection so my custom template is called field-collection-item--field_video_collection.tpl.php.

I then can treat it as I would a node template by rendering individual field collection items within that template, e.g.

<?php print render($content['field_video_thumb_col']); ?>
<?php print render($content['field_video_file_col']); ?>

etc...

The only extra thing you may need to do is some exclusions within the matching node template for the content type e.g.

hide($content['field_video_thumb_col']);
hide($content['field_video_file_col']);

... but I am not actually sure if that's necessary, I am still learning how to do all this. Now if I could only get this worked out: #1966732: Trying to create a variable for and render the File ID [FID] of a Field Collection filefield item

jack-pl’s picture

@highrockmedia Yes I have, and you're right, it should be done in field-collection-item--[field collection name].tpl.php file, but what about multi collections? Let say, I have a field collection with 3 items:

  • Tile
  • Image
  • Description

It is a multiple field collection and would contain for example 2 values:

  • Value #1
    • Tile #1
    • Image #1
    • Description #1
  • Value #2
    • Tile #2
    • Image #2
    • Description #2

I'd like to theme this field collection in one template file, so I need to get all these values one by one, and it should be possible to do that in foreach loop, but if you will try to do that in field-collection-item--field_name.tpl.php file, for example:

 
 $collections = array();
 
 foreach ($content as $k =>$v){
		
		$item_wrapper = entity_metadata_wrapper('field_collection_item', $v['#object']);
		
		$field_title 		= $item_wrapper->field_title->value(); 
		$field_image 		= $item_wrapper->field_image->value();
		$field_description	= $item_wrapper->field_description->value();								
		
		$collection = array('title'			=>	$field_title,
							'image_url'		=>	$field_image['uri'] ? file_create_url($field_image['uri']):'',
							'description'	=>	$field_description
						);
		$collections[] = $collection;
	
	
}
// take a look what you get
print '<pre>' . print_r($collections,1) . '</pre>';

then you will get as many arrays as collections, in this example each collection will be created twice, because field has two collections, something like this:

Array
(
	[0] => Array
		(
			[title] => Title #1
			[image_url] => ...url_to_image.../img1.jpg
			[description] => description #1
		)
	
	[1] => Array
		(
			[title] => Title #1
			[image_url] => ...url_to_image.../img1.jpg
			[description] => description #1
		)
)

Array
(
	[0] => Array
		(
			[title] => Title #2
			[image_url] => ...url_to_image.../img2.jpg
			[description] => description #2
		)
	
	[1] => Array
		(
			[title] => Title #2
			[image_url] => ...url_to_image.../img2.jpg
			[description] => description #2
		)
)


but if you do that as I mentioned in post #51 then you will get all field collections with the values in one array, e.g:

Array
(
	[0] => Array
		(
			[title] => Title #1
			[image_url] => ...url_to_image.../img1.jpg
			[description] => description #1
		)
	
	[1] => Array
		(
			[title] => Title #2
			[image_url] => ...url_to_image.../img2.jpg
			[description] => description #2
		)
)

Maybe I miss something, because I'm sure it should be possible to do that in field-collection-item--[field collection name].tpl.php

danny englander’s picture

StatusFileSize
new544.35 KB

@ jack-pl - Yes, you can render all the fields of a collection in one template (and if there are multiple collection items within one node.)

For example, I have three videos, associated images and titles but I did not need to use any loop code, it seems the template already does the loop for you (see my screen capture), I think it's similar to multiple items for one field in a custom Views template.

So perhaps field-collection-item--field_name.tpl.php is misleading, it should probably be plural but I guess that would be a change in the module code itself.

jack-pl’s picture

@ highrockmedia - Yes, you're right - and that's the point. Field template (not field collection template) already does the loop. If someone need to custom the field collection with his own loop, then he can do that only in field--[field collection name].tpl.php file.

Also there is a possibility to to theme field collection with node object.

jack-pl’s picture

/**
 * Show all field collection values from node object
 * Example field collection name: "field_helloworld"
 * Example fields within a field collection:
 *  - field_title       (string)
 *  - field_image       (image)
 *  - field_description (string)
 */

// get node object
$node = menu_get_object();

// get field collections from node 
$field_helloworld = field_get_items('node', $node, 'field_helloworld');

// get all fields values if collection exists
if (!empty($field_helloworld)){
    $field = field_view_value('node',$node, 'field_helloworld', $field_helloworld[0]);  
    foreach ($field['entity']['field_collection_item'] as $id => $field_collection){

        // load the field collection item entity
        $field_collection_item = field_collection_item_load($id);
        // wrap the entity and make it easier to get the values of fields
        $field_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);

        // all values from a field collection
        $field_title        = $field_wrapper->field_title->value();
        $field_image        = $field_wrapper->field_image->value(); // an array of image data
        $field_description  = $field_wrapper->field_description->value(); 

        // an example of getting image url from field_image
        $image_url          = $field_image['uri'] ? file_create_url($field_image['uri']) : '';
    }
}

Notice: There is no "['und']['0'][value]"

Pimmy’s picture

I am sorry to ask such a basic question - but would anyone be able to suggest why my $content variable is totally empty in my field--field_payment_request.tpl.php file (the field collection is called 'field_payment_request')?

If I use $items, is set and returns all the fields of the field collection:

<?php
foreach ($items as $delta => $item) {
  print render($item) . t('foo'); 
} 
?>

However if I use $content['field_payment_request'], it is empty not allowing me to loop through the field collections and theme them:

<?php
if (empty($content)) {
  print 'No data available';
}
?>

I must be missing something very obvious..

(Ultimately I want to create a table with columns the field collection fields, and rows for each field collection.)

jack-pl’s picture

Your tpl file name should contain hyphens instead underscores:
change the name of the file from: field--field_payment_request.tpl.php to field--field-payment-request.tpl.php

Pimmy’s picture

Thanks for the tip - I've changed the filename from using underscores to hyphens but it doesnt seem to make any difference. I had to clear the cache after the change in the filename, but after clearing the cache, the behaviour is exactly the same - $content is not set.

The piece of code which I play around with is this:

<?php
print '<table>';
print '<tr><td><p><b>Request Type</b></p></td><td><p><b>Date of Request</b></p></td><td><p><b>Amount</b></p></td></tr>';
if (empty($content)) {
  print '<tr><td colspan="3"><p>No data available</p></td></tr>';
}

if (!empty($content['field_payment_request'])) {
  print '<tr>';
  foreach ($content['field_payment_request']['#items'] as $entity_uri) {
    $a_field_collection_item = entity_load('field_collection_item', $entity_uri);

    //Now you have a variable with the entity object loaded in it, and you can do stuff. 
    foreach ($a_field_collection_item as $a_field_collection_item_object ) {
      print '<td><p>' . render($a_field_collection_item_object) . '</p></td>'; 
    }
  }
  print '</tr>';
} else {
    print '<td colspan="3"><p>No payments have been requested yet.</p></td>';
}
print '</table>';
?>

and the output is:

Request Type | Date of Request | Amount
No data available
No payments have been requested yet.

jack-pl’s picture

sorry, i forgot that is the field collection file, so the name should be: field-collection-item--field-payment-request.tpl.php

Pimmy’s picture

Thanks Jack,

That did it, however I could not workout the $content parsing - it just never worked. I have tried one of the examples in your earlier posts using $items in field_payment_request.tpl.php.

<?php
// find items and push them to their arrays
print '<table>';
print '<tr><td><p><b>Request Type</b></p></td><td><p><b>Date of Request</b></p></td><td><p><b>Amount</b></p></td></tr>';

foreach ($items as $fields) {
    
    foreach ($fields['entity']['field_collection_item'] as $elements) {
        
        print '<tr>';
        
        $field_request_type = isset($elements['field_payment_request_type']['#object']->field_payment_request_type['und'][0]['taxonomy_term']->name) ? 
                            $elements['field_payment_request_type']['#object']->field_payment_request_type['und'][0]['taxonomy_term']->name :
                            '';

        $field_request_date = isset($elements['field_payment_request_date']['#object']->field_payment_request_date['und'][0]['value']) ? 
                            $elements['field_payment_request_date']['#object']->field_payment_request_date['und'][0]['value'] :
                            '';

        $field_request_amont = isset($elements['field_payment_request_amount']['#object']->field_payment_request_amount['und'][0]['value']) ? 
                            $elements['field_payment_request_amount']['#object']->field_payment_request_amount['und'][0]['value'] :
                            '';    
        
        print '<td><p>' .$field_request_type . '</p></td>';
        print '<td><p>' .$field_request_date . '</p></td>';
        print '<td><p>' .$field_request_amont . '</p></td>';
        
        print '<tr>';
    }
}

print '</table>';
?>

That created a nice table listing all the collections in rows.

Cheers,

Pimmy

jack-pl’s picture

Version: 7.x-1.0-beta5 » 7.x-1.x-dev

It would be better if you will keep away the logic from .tpl files.
You can put this logic to preprocess_field function in your template.php file:

/**
 * Override or insert variables into field templates.
 */
function YOURTHEME_preprocess_field(&$variables) {
  $element = $variables['element'];	
  if ($element['#field_name'] == 'field_payment_request') {
    $payments = array();
    foreach ($variables['items'] as $fields) {
      foreach ($fields['entity']['field_collection_item'] as $elements) {

        $field_request_type = isset($elements['field_payment_request_type']['#object']->field_payment_request_type['und'][0]['taxonomy_term']->name) ? 
        $elements['field_payment_request_type']['#object']->field_payment_request_type['und'][0]['taxonomy_term']->name : '';

        $field_request_date = isset($elements['field_payment_request_date']['#object']->field_payment_request_date['und'][0]['value']) ? 
        $elements['field_payment_request_date']['#object']->field_payment_request_date['und'][0]['value'] : '';

        $field_request_amont = isset($elements['field_payment_request_amount']['#object']->field_payment_request_amount['und'][0]['value']) ? 
        $elements['field_payment_request_amount']['#object']->field_payment_request_amount['und'][0]['value'] : '';

        $payments[] = array(
          'type' => $field_request_type,
          'date' => $field_request_date,
          'amont' => $field_request_amont
        );
      }
    }
    $variables['payments'] = $payments;
  }
}

Then, in the field--field-payment-request.tpl.php :

<table>;
  <tr>
    <td><p><b>Request Type</b></p></td>
	<td><p><b>Date of Request</b></p></td>
	<td><p><b>Amount</b></p></td>
  </tr>';
  
  <?php foreach ($payments as $key => $payment) : ?>
    <tr>
      <td><p><?php print $payment['type']; ?></p></td>
      <td><p><?php print $payment['date']; ?></p></td>
      <td><p><?php print $payment['amont']; ?></p></td>
    <tr>
  <?php endforeach; ?>
</table>
tying200’s picture

i want to theme the profile2 type eidt.tpl.php
i build a page--porfile-resume.tpl.php and fix the code for copying the page.tpl.page,
How to do next?
i need the field-collection-item--eidt.tpl.php but no page
this table is very troublesome, how to fix theme only div+css

table id="field-pay-values" class="field-multiple-table sticky-enabled tabledrag-processed tableheader-processed sticky-table">
<thead>
<tr>
<th class="field-label" colspan="2">
<label>收款方式 </label>
</th>
<th class="tabledrag-hide" style="display: none;">Order</th>
</tr>
</thead>
<tbody>
<tr class="draggable odd">
<td class="field-multiple-drag">
<a class="tabledrag-handle" href="#" title="Drag to re-order">
<div class="handle"> </div>
</a>
</td>
<td>
<div id="edit-profile-resume-field-pay-und-0-field-bankname" class="field-type-list-integer field-name-field-bankname field-widget-options-select form-wrapper">
<div id="edit-profile-resume-field-pay-und-0-field-bankaddr" class="field-type-text field-name-field-bankaddr field-widget-text-textfield form-wrapper">
<div id="edit-profile-resume-field-pay-und-0-field-bankuser" class="field-type-text field-name-field-bankuser field-widget-text-textfield form-wrapper">
<div id="edit-profile-resume-field-pay-und-0-field-bankcard" class="field-type-text field-name-field-bankcard field-widget-text-textfield form-wrapper">
<input id="edit-profile-resume-field-pay-und-0-remove-button" class="form-submit ajax-processed" type="submit" value="Remove" name="profile_resume_field_pay_und_0_remove_button">
</td>
<td class="delta-order tabledrag-hide" style="display: none;">
<div class="form-item form-type-select form-item-profile-resume-field-pay-und-0--weight">
<label class="element-invisible" for="edit-profile-resume-field-pay-und-0-weight">Weight for row 1 </label>
<select id="edit-profile-resume-field-pay-und-0-weight" class="field_pay-delta-order form-select" name="profile_resume[field_pay][und][0][_weight]">
</div>
</td>
</tr>
</tbody>
</table>
derKonrad’s picture

Version: 7.x-1.x-dev » 7.x-1.0-beta5

Hi,

i tried solution [#47] and it kinda worked. The only issue:

$elements['field_xyz']['#object']->field_xyz['und'][0]['value']

only returns a number of the selected item (its a radio button). How can I access the actual value?

Thanks!

derKonrad’s picture

solution for radio buttons (and all other kinds):

file: field--[name-of-your-field-collection-field].tpl.php

foreach ($items as $fields){
    foreach ($fields['entity']['field_collection_item'] as $elements) {
        print $elements['field_server'][0]['#markup']; // radio button field
        print $elements['field_cpl'][0]['#markup']; // text field
    }
}
MickL’s picture

Im still not able to remove the wrappers. The #2 unset method sounds very nice, but i dont get it to work. What do you mean with "content type tpl" ? I tried it inside of my node.tpl and page.tpl but it doesnt work.

bjuncosa’s picture

Version: 7.x-1.x-dev » 7.x-1.0-beta5

Yup. The only difference is that the entity type is "field_collection_item" instead of "node" or "user" (as the documentation lists).

bjuncosa’s picture

@pinder (#49)
It's possible to theme a field in a field collection using field_view_field().
The only difference is that the entity type is "field_collection_item" instead of "node" or "user" (as the documentation lists).

a77icu5’s picture

In the example, using entity_load render($a_field_collection_item_object->field_1) doesn't render anything because the content is not a renderable array.

Denise_0523’s picture

I tried all the solutions above, but none is for me , I have a field collection field_productnav with 2 items field_title and field_body, that is
field_productnav
field_title
field_body
there are many values in field_title, I want to get all the values in field_title, now I can get all the values as a string

foreach($content['field_productnav'][0]['entity']['field_collection_item'] as $field_collection_item)  {
    print render($field_collection_item['field_title']);
    print render($field_collection_item['field_body']);
    }	

but i want get every value into a array, how should i do?
if i use following code, i just get ['und'][0]['value'],

if(!empty($content['field_productnav']['#items']))
foreach($content['field_productnav']['#items'] as $item) {
        // because field items are numbered consecutively, the correct index needs to be retrieved here
        $index=$item['value'];  
        // replace 'field_field1' with your field name
        $field1[]=$content['field_productnav'][$item_count]['entity']['field_collection_item'][$index]['field_title'][0]['#markup'];
        // replace 'field_field2' with your field name
        $field2[]=$content['field_productnav'][$item_count]['entity']['field_collection_item'][$index]['field_body'][0]['#markup'];
		$item_count++;
 }

but about ['und'][1]['value'], ['und'][1]['value']....? i don't know how to use loop to get them

aucovic’s picture

After 10 loooong hours of banging my head against the wall trying to theme my collection field, I finally came up with solution that works.

First of off all, none of above's examples work, so this is what I've done:

1. used field-collection-item--[your-collection-field].tpl.php
2. wrote something simple as this:

print '<div class="my-custom-class">';
print $content['your_field_1']['#items'][0]['value'] . ', ';
print $content['your_field_2']['#items'][0]['value'] . ', ';
print $content['your_field_3']['#items'][0]['value'];
print '</div>';

(Note that your_field_1, your_field_2, etc.. are subfields of your field collection)

3. Since I'm using views to redner this field I setup 3 things in UI field settings:
3.1. Formatter > Fields only
3.2 MULTIPLE FIELD SETTINGS > Display all values in the same row
3.3 MULTIPLE FIELD SETTINGS > Simple separator > Leave this empty if you do not want additional markup nor wrappers around each collection set.

4. Had a LARGE beer!

Aljullu’s picture

#71 It worked for me. Thank you!

#10 It's not the best way, but I could remove it modifying the module code. You have to delete this line (in my case it was line 1214):
$element[$delta]['#theme_wrappers'] = array('field_collection_view');
from field_collection.module.

gusantor’s picture

Issue summary: View changes

I just need to add a class to field collection item (FCI), so reach here but found no easy way to do it

looking around I came accross with template_preprocess_entity (or which I think it is mytheme_preprocess_entity)

using this function at template.php I was able to add a class for each item using

function mytheme_preprocess_entity(&$vars) { 
  if($vars['elements']['#bundle']=="my_field_collection" && $vars['elements']['#entity_type']=="field_collection_item"){
    $vars['classes_array'][] = "my-class".$vars['elements']['#entity']->item_id;
    #dpm($vars);
  }
}

cheers !

delta’s picture

Try inline_entity_display module to control the fields of your field collection directly on the parent entity bundle manage display form.

priyanka12chavan’s picture

#71 worked for me for adding custom classes to field collection. Thanks!

sijuwi’s picture

#71 works...but it does not output text formats associated with that field.

jmlavarenne’s picture

This will make a render array for each field in your field collection.

In your template file you can do this:

<?php print render($row['field_fieldname']); ?>
<?php
/**
 * Implements hook_preprocess_field().
 */
function THEMENAME_preprocess_field(&$variables) {
  // Generate a renderable array for each field in the field collection.
  if ($variables['element']['#field_name'] == 'YOUR_FIELD_NAME') {
    $variables['theme_hook_suggestions'][] = 'field__SUGGESTION';

   // If you need it, this will create a separate suggestion for each node type where the collection is used.
    $variables['theme_hook_suggestions'][] = 'field__SUGGESTION__' . $variables['element']['#bundle'];

   // Custom function that provides a render array for each field in the field collection, similar to the $content variable for nodes.
    _THEME_rows_from_field_collection($variables, 'field_location');
  }
}

/**
 * Creates render array rows array from a field collections.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $field_name
 *   The name of the field collection field being altered.
 */
function _THEME_rows_from_field_collection(&$variables, $field_name) {
  $fields = field_info_instances('field_collection_item', $field_name);
  $variables['rows'] = array();
  foreach($variables['element']['#items'] as $key => $item) {
    $entity_id = $item['value'];
    $entity = field_collection_item_load($entity_id);

    // Generate a render array for each field.
    $row = array();
    foreach(array_keys($fields) as $field_name) {
      $row[$field_name][] = field_view_field('field_collection_item', $entity, $field_name, $display = array(), $langcode = NULL);
    }
    $variables['rows'][] = $row;
  }
}
?>

// TEMPLATE FILE
<?php foreach ($rows as $delta => $row): ?>
  <?php //kpr($row); ?>
  <div class="row location">
    <div class="col-xs-9">
      <h3><?php print render($row['FIELD_NAME_X']); ?></h3>
      <div class="XYZ"><?php print render($row['FIELD_NAME_Y']); ?></div>
      <div class="address-2">Cambridge, MA 02138</div>
    </div>
  </div>
<?php endforeach; ?>
flyke’s picture

I needed to remove unwanted wrappers created by field collections.

I ended up creating a patch that removes them from field_collection.module.
This was the easiest way.

nadeeke’s picture

how to set metatag image field with fieldcollection image [field_collection_item:field-main-image]

jdleonard’s picture

I'm not sure, but the Field Collection List Formatter module might be helpful for anyone still looking.

karimiehsan1819’s picture

StatusFileSize
new8.73 KB

hi , i want hide or remove label and border of field collection , how can i do them?

iamkirkbater’s picture

Looks like this hasn't been said yet. Simple way to override the default cascading, if you're not using the bundle.tpl.php files:

//Add this to your themes template.php file
function myTheme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  // Add specific suggestions that can override the default implementation.
  $variables['theme_hook_suggestions'] = array(
    'field__' . $element['#field_type'],
    'field__' . $element['#field_name'],
    // note that 'field__'.$element_['#bundle'] is removed here.  This prevents cascading, but if you already rely on this functionality it will break.
    'field__' . $element['#field_name'] . '__' . $element['#bundle'],
  );
}
misikir’s picture

#31 is working for me in node.tpl.php

jomarocas’s picture

#71 today no working i rename the file in 5 times, with various name
the field collection name is field_item

field-collection-item--field-items.tpl.php
field-collection-item--field_items.tpl.php
field_collection_item__field_items.tpl.php
field_collection_item__field-items.tpl.php
field--field-items.tpl.php
field--field_items.tpl.php

sorry wrong template

this is the form to call tpl in field collection
field-collection-item--field-items.tpl.php

jeffglenn’s picture

@jomarocas If I'm understanding correctly you'll need to have your template named:
field-collection-item--field_item.tpl.php

In that file you'll be able to print the individual fields associated with the Field Collection using:
<?php print render($content['field_name']); ?>

Be sure and flush your cache so Drupal recognizes the new template. Hope this helps!

Katy Jockelson’s picture

#50 works well for me to print all the items in a field collection in a node template file. And easily add extra html to affect layout etc. Thanks @Trias2013!

I'm also printing a wrapper div that has a class showing which number item this is (0,1, 2 etc) using the value of $i.

I'm wondering if there's a simple line of logic I could add in to this to give me an integer for the total number of items in the field collection - so I can then add that as an overall class to a wrapper around the lot (for CSS purposes). Any help greatly appreciated. And in plain English please, I'm not a php coder :)

jmlavarenne’s picture

$total = count($content['field_collection']);

This should do it for you. $total will hold the number of items in your field collection, so you can do this in you template:

<div class="collection-count-<?php print $total; ?>">
mattjbondi’s picture

Taking bits and pieces from above - I have got this to work for images in a field collection in the main .tpl file for the node that contains the field collection:

if (isset($node->field_gallery_images)) {
  $nodeField = field_get_items('node', $node, 'field_gallery_images');
  if (!empty($nodeField)) {
    foreach ($nodeField as $key => $item) {

      $field_collection_item = field_collection_item_load($item['value']);
      $item_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);
                                
      print '<div class="yourCustomClass">';
      $field_image = $item_wrapper->field_gallery_image->value();
      //print_r($field_image);
      print theme('image_style', array('style_name' => 'large', 'path' => $field_image['uri'])); 
      print '</div>';
    }
}
andyanderso’s picture

Thanks for the summary mattjbondi - That was super helpful and works great for me!

khurrami’s picture

#52 helped me
Thanks a lot