Automatically recompute a computed field value on a referenced entity on saving the referencing entity

Created on 27 August 2023, about 1 year ago

Problem/Motivation

I would like to force to automatically recompute a computed field value on a referenced taxonomy entity on saving the referencing content entity (that is: without manually resaving the referenced taxonomy entity).

Steps to reproduce

1. I have a content type called "transaction", with a "field_amount" and a "field_cost_type" referencing the "cost_type" taxonomy entity.
2. The taxonomy called "cost_type" has a computed field called "field_total_cost_type". The taxonomy vocabulary is hierarchical (like Car > Fuel, Car > Insurance, etc.)

The "field_total_cost_type" on a cost_type taxonomy term calculates the total of "field_amount" values from the referencing transaction entity. This value should be recomputed whenever a new content entity of type transaction is inserted, updated or deleted.

The code below works well, but is only triggered if I manually resave the cost_type taxonomy entity.

/**
* Computed fields on Total cost type taxonomy
*/

function computed_field_field_total_cost_type_compute($entity_type_manager, $entity, $fields, $delta) {
    $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
    if(empty($entity->field_total_cost_type->value) || $entity->field_total_cost_type->value == 0) {
		$children = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadChildren($tid);
		$value = 0;
		//if term has children, display total from children field_total_cost_type, otherwise display total from referencing nodes' field_amount
		if(!empty($children)) {
			foreach ($children as $child) {
				$value +=  $child->field_total_cost_type->value;
			}
		}
		else {
			$results = \Drupal::entityQuery('node')
				->accessCheck(FALSE)
				->condition('type', 'transaction')
				->condition('field_cost_type.entity:taxonomy_term.tid', $tid)
				->execute();
			foreach ($results as $entity_id) {
				$value +=  \Drupal\node\Entity\Node::load($entity_id)->field_amount->value;
			}
		}
	}
	else $value = $entity->field_total_cost_type->value;
	return $value;
}

Remaining tasks

How can I trigger the recalculation of the computed field value on the referenced taxonomy term entity whenever the referencing transaction entity is inserted, updated or deleted?

💬 Support request
Status

Active

Version

3.0

Component

Documentation

Created by

🇮🇪Ireland marksmith

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024