1

Please bare with a very recent user of Drupal.

I want to create an array out of all examples of the string "url" on a Drupal site.

I've used the method "field_get_items" previously to do something very similar, but I am now trying to access a field collection that is many levels deep into the node's array and I'm not sure that method would work.

$website_urls = array();
$faculty_members = field_get_items('node', $node, 'field_faculty_member');
for ($i = 0; $i < count($faculty_members); $i++) {
    $value = field_view_value('node', $node, 'field_faculty_member', $faculty_members[$i]);
    $field_collection = $value['entity']['field_collection_item'][key($value['entity']['field_collection_item'])];
    $website_urls[] = render($field_collection['field_link']['#items'][0]['url']);
}

An example of one url's location is...

['field_faculty_program'][0]['entity']['field_collection_item'][1842]['field_faculty_member'][0]['entity']['field_collection_item'][1843]['field_link']['#items'][0]['url']

..and another...

['field_faculty_program'][4]['entity']['field_collection_item'][1854]['field_faculty_member'][0]['entity']['field_collection_item'][1855]['field_link']['#items'][0]['url']

What is the method I should be using to collect al of the 'url' strings for placement in an array?

1 Answers1

0

You can actually still use the field_get_items() function but eventually pass it 'field_collection_item' instead for the node type.

Something like this should work:

if ($items = field_get_items('node', $node, 'field_faculty_member')) {

  //loop through to get the ids so we can take
  //advantage of field_collection_item_load_multiple for
  //greater efficiency
  $field_collection_item_ids = array();
  foreach ($items as $item) {
    $field_collection_item_ids[] = $item['value'];
  }

  if ($field_collection_items = field_collection_item_load_multiple($field_collection_item_ids)) {
    foreach ($field_collection_items as $subitem) {

      //now we load the items within the field collection
      if ($items = field_get_items('field_collection_item', $subitem, 'field_faculty_member')) {

        //And you can then repeat to go deeper and deeper 
        //e.g. a field collection item within a field collection
        //for instance to get the urls within your faculty members
        //item. Best to break this into functions or a class
        //to keep your code readable and not have so many nested
        //if statements and for loops

      }

    }
  }

}

Hope that helps!

Scott

scott
  • 1,068
  • 1
  • 9
  • 20