I'm trying to add a computed field to a Field collection where some data would come from the host entity. Something like:

// Data from the field collection: it works!
$value_from_collection = $entity->field_value_1[LANGUAGE_NONE][0]['value'];

// Data from the host node: I don't know what to put here
$value_from_node = $host->field_value_2[LANGUAGE_NONE][0]['value'];

$output = ($value_from_collection + $value_from_node);

I've been fiddling with entity_load(), entity_metadata_wrapper(), to no avail: I'm no php guru.

Any idea?

Comments

Tharna’s picture

You can access host using $entity->hostEntity() method.

function computed_field_field_fieldname_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
   $value_from_collection = $entity->field_value_1[LANGUAGE_NONE][0]['value'];
   $host = $entity->hostEntity( );
   $value_from_node = $host->field_value_2[LANGUAGE_NONE][0]['value'];
   $entity_field[0]['value'] = $value_from_collection + $value_from_node;
}
yul63’s picture

Thank you very much, it works.

For other php semi-litterates like me, the function that encloses the values is not needed in the context of a computed field in a Field collection. So

$host = $entity->hostEntity( );
$value_from_node = $host->field_value_2[LANGUAGE_NONE][0]['value'];
$entity_field[0]['value'] = $value_from_node;

will get the value of the field in the host entity.

Side note out of topic: if there is no value in a non mandatory field queried by the code, the computed field will start spewing error messages even though it might work.

$host = $entity->hostEntity( );
if (isset($host->field_value_2[LANGUAGE_NONE][0]['value'])) {
$value_from_node = $host->field_value_2[LANGUAGE_NONE][0]['value'];
}
else {
$value_from_node = '';
}

$entity_field[0]['value'] = "$value_from_node";

will return an empty string if there's nothing in the field.

jmuzz’s picture

Issue summary: View changes
Status: Active » Fixed

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.