Hawxby
Hawxby

Reputation: 2804

Rendering individual FieldCollectionItemEntity fields

I need to render individual fields from a field collection to allow me to tweak the field order, field contents, remove wrapping DOM nodes, etc depending on certain criteria.

I've been reading through this thread as it seems to be the best resource on the matter but I cannot figure out why this field collection renderer is not behaving.

It simply outputs nothing.

node--component-icon-promo.tpl.php

<? if (!empty($content['field_icon_promo_items'])) : ?>

  <div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

    <?php foreach ($content['field_icon_promo_items']['#items'] as $entity_uri): ?>
      <?php 
        $item = entity_load('field_collection_item', $entity_uri); 
      ?>

      <?php foreach ($item as $item_object ): ?>

        <?php print render($item_object->field_cta); ?>

      <?php endforeach; ?>
    <?php endforeach; ?>

  </div>

<? endif; ?>

Adding a dpm($item_object); right before the print render outputs this.

Field output

And changing the <?php print render($item_object->field_cta); ?> to <?php print render($item_object); ?> just results in errors.

Recoverable fatal error: Object of class FieldCollectionItemEntity could not be converted to string in include() (line 99 of /var/www/html/sites/all/themes/xerox/templates/node--component-icon-promo.tpl.php).

I know that's because the $item_object is just that, an object which render doesn't like. The field collection bit of the API just seems like a total mess.

Any help would be much appreciated.

Upvotes: 0

Views: 333

Answers (1)

Anurag
Anurag

Reputation: 555

Would suggest to use it like this way, using entity_metadata_wrapper:

<? if (!empty($content['field_icon_promo_items'])) : ?>

  <div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

    <?php foreach ($content['field_icon_promo_items']['#items'] as $entity_uri): ?>
      <?php 
        $item = entity_load('field_collection_item', $entity_uri);
      ?>

      <?php foreach ($item as $item_object ): ?>

        <?php 
            $wrapper = entity_metadata_wrapper('field_collection_item', $item_object);
            $field_cta = $wrapper->field_cta->value(); 
            //render your values with your own html or using theme_link function
        ?>

      <?php endforeach; ?>
    <?php endforeach; ?>

  </div>

<? endif; ?>

For more help on meta data wrapper visit this link

Upvotes: 1

Related Questions