1

I have an entity with a field colleciton (fc_details), and in that field collection I have fields amount(field_amount) and Type (field_type)

There are several examples to sum up field colleciton values in computed field like:

$sum = 0;
$wrapper = entity_metadata_wrapper($entity_type, $entity);
  foreach($wrapper->field_fc_details as $collection) {
    $sum += $collection->field_amount->value();
  }

$entity_field[0]['value'] = $sum; 

But I want to sum up values, where field_type values = "Z".

I tried variations of "if($wrapper->field_type->value()='Z' " inside foreach, but then site gives 500 error.

Any ideas ? Thanks in advance.

1

Try the following and let me know how you go.

if($collection->field_type->value() == 'Z') {
  $sum += $collection->field_amount->value();
}
  • Unfortunately I've tried this and this throws 500 error and "Undefined variable: colletion.." error as well. – INTANK Mar 13 '17 at 23:44
  • Did you try clearing the cache? Also can you please add what's in your error log. – Ash U Mar 13 '17 at 23:45
  • Cache cleared. with $wrapper trial, I only get 500 Error. There is no additional error in log. While trying with $collection, it gives 500 error + undefined variable for collection + Trying to get property of non-object error. – INTANK Mar 13 '17 at 23:52
  • can you do a print_r of collection object and see what variables are available? – Ash U Mar 13 '17 at 23:58
0

OK, I solved the problem by this way: When I try to fetch the value inside the if condition, it throws 500 error. So I first assigned a variable to the control value and used it in if condition, it worked.

$sum = 0;
$wrapper = entity_metadata_wrapper($entity_type, $entity);
  foreach($wrapper->field_fc_details as $collection) {
   $type = $collection->field_type->value();
   if ($type == 'Z'){  
    $sum += $collection->field_amount->value();
   }
  }
$entity_field[0]['value'] = $sum; 

Still couldn't get the reason, but it works.

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.