Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Hi there,
I'm in a bit of a bind with computed field and the entity reference modules (both latest version 7 releases). I'm not too great with PHP and I would appreciate any help I can get on this matter. I am going to post this in both modules' issue queue, as I am not certain who might be able to help better.
What I'm trying to do is:
- I have 2 content types, let's call them CT1 and CT2.
- CT1 has a 'price' field in it (decimal).
- In CT2, I have a multi value entity reference field, where a user can select multiple nodes from CT1.
- Then in CT2, I have a computed field, where I need to calculate the sum price of all the nodes selected in the above mentioned entity reference field.
I need to know what exactly to put in my computed field's 'Computed Code (PHP)' field.
- Let's call the 'Price' field in CT1 field_ct1_price
- And let's call the Entity Reference field in CT2 field_ct2_select_ct1
This is what I have so far (using multiple snippets found online):
$sum = 0;
$wrapper = entity_metadata_wrapper($entity_type, $entity);
foreach($wrapper->field_ct2_select_ct1 as $related_entity) {
$sum += $related_entity->field_ct1_price->value();
}
$entity_field[0]['value'] = $sum;
Can anybody tell me what I am doing wrong, or just call me stupid and help me anyway?
Thanks!
Comments
Comment #1
manu manuWith a multi-value reference field, EntityMetadataWrapper is returning an Iterator. You should try this way:
Check out this page it contains some very useful documentation.
Comment #2
Ahmad AlSabhany CreditAttribution: Ahmad AlSabhany commentedHello, I need this feature since the D8 doesn't include a proper method of calculating values in views.
The issue is that the field that references the "entity" has to be set to "unlimited" in my case. Therefore, calling entities statically (by title) is not going to work for me. I need a dynamic way to access specific fields (price, amount) of each referenced entity, which then I will use to report a computed value.