3

I have a node with a field type field_collection which has 2 items:

$node->field_field_collection['und'] = array(
  0 => array('value' => 1),
  1 => array('value' => 2),
);

on the save node drupal fire hook_node_presave:

/**
 * Implementation of hook_node_presave.
 */
function mymodule_node_presave($node) {
  $ewrapper = entity_metadata_wrapper('node', $node);
  $wrapper_counter = 0;
  $node_counter = 0;
  foreach ($ewrapper->field_field_collection->getIterator() as $delta => $fc_wrapper) {
    $wrapper_counter++;
  }
  foreach ($node->field_field_collection['und'] as $key => $value) {
    $node_counter++;
  }
}

after runing code

$wrapper_counter = 0;
$node_counter = 2;

what am I doing wrong?
I want to walk the field collection using entity_metadata_wrapper.

Drupal: 7.34
Entity API: 7.x-1.5
Field collection: 7.x-1.0-beta8

  • EntityListWrapper is iterrable, why the need for ->getIterator()? – Clive Feb 17 '15 at 14:56
  • how to use it ? – masdzen Mar 6 '15 at 11:48
  • I don't understand the question. If your question has changed, please click the "edit" link and update it that way – Clive Mar 6 '15 at 11:51
  • how do I bypass the "field collection" using your answer? "EntityListWrapper is iterrable, why the need for ->getIterator()?" – masdzen Mar 6 '15 at 11:55
  • It wasn't an answer, it was a comment asking you to clarify your choice to use getIterator() – Clive Mar 6 '15 at 12:01
1

By this way as per this post:

/**
 * Implementation of hook_node_presave.
 */
function mymodule_node_presave($node) {
  if ($node -> type == 'my_type') {
    $field_field_collection = field_get_items('node', $node, 'field_field_collection');
    foreach ($field_field_collection as $key => $value) {
      $fc_wrapper = entity_metadata_wrapper('field_collection_item', $value['entity']);
      $fc_name = $fc_wrapper -> field_field_collection_name -> value();
      dsm($fc_name);
    }
  }
}

See: Understanding Field Collection Values and Entity metadata wrappers pages.

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.