I have a field collection named values. It contains the fields:

  • Amount
  • Price
  • Total

The "Total" field calculates the Price*Amount.

Now I created a new field outside the field collection called "Subtotal".

How do I sum all the values of the "Total" field in a node to populate "Subtotal"? I tried a lot of code which I found but none seem to work.

I tried this code but it gives as a warning: undefined index at line 5

$field_items = field_get_items($entity_type, $entity, 'field_values');
$total = 0;
foreach ($field_items as $item)
  $total += $item['field_total']['und'][0]['value'];
$entity_field[0]['value'] = $total;

Thank you in advance!

  • I see some typos/mistakes in your code. You missed to mention $ for total variable (at line 2). and there should be field_total (I guess) instead of field_amount.(line 1) – Krishna Mohan Mar 16 '15 at 13:02
  • Hi! I made some mistakes in the posted code. I hope it is clear now. So my field collection field_values contains a field field_total where I need the sum off. I found this calculation but it does not seem to work. – Erik van der Bas Mar 16 '15 at 15:15

I've got it! After a lot of tries I found a solution: This works for a computed field outside the collection.

$sum = 0;
$wrapper = entity_metadata_wrapper($entity_type, $entity);
foreach($wrapper->field_values as $collection) {
   $sum += $collection->field_total->value();
$entity_field[0]['value'] = $sum;

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