5

My content type uses a field collection (field_site_web) to allow users to enter multiple websites, consisting of a name (field_site_name) and an internet connection (field_link).

I want to use a foreach() loop to get those value, but I do not know how to access these fields. How can I do?

EDIT

how can I do to avoid the error in the line of the foreach? I tried so, but does not work:

if($fc_fields != false){
  // Extract the field collection item ids
  $ids = array();
  foreach ($fc_fields as $fc_field) {
    $ids[] = $fc_field['value'];
  }
}
12

The field collection is an entity in it's own right; the values stored against your node are a list of field collection item ids that you'll need to load manually to loop over. Something like this:

// Get the field collection items.
$fc_fields = field_get_items('node', $node, 'field_field_collection_field');

// Extract the field collection item ids
$ids = array();
foreach ($fc_fields as $fc_field) {
  $ids[] = $fc_field['value'];
}

// Load up the field collection items
$items = field_collection_item_load_multiple($ids);

// Loop through the items and extract field values
foreach ($items as $item) {
  $link_fields = field_get_items('field_collection_item', $item, 'field_link');
  $link = array_shift($link_fields);
  $url = $link['url'];

  $site_name_fields = field_get_items('field_collection_item', $item, 'field_site_name');
  $site_name = array_shift($site_name_fields);
  $name = $site_name['value'];
}
  • Hello, sorry, can i see how you manage to print the field_link and field_site_name? – Antilope Jun 28 '12 at 9:30
  • I've updated the answer to extract both fields...basically you just need to print $url and print $name in the loop – Clive Jun 28 '12 at 9:34
  • I found this error: $ url = $ link ['value']; thanks for your invaluable help! – Antilope Jun 28 '12 at 9:43
  • how can I do to avoid the error in the line of the foreach? – Antilope Jun 28 '12 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.