Hi,

I'm new to Drupal so I apologize if this question is very basic. This question is for Drupal 8.

I would like to be able to change the value of a Field before the node is displayed. This particular field is dynamically calculated, so it is not intended to be stored. My assumption was that I would change the value in the entity in either the hook_node_view_alter or hook_view_alter, and that value would then be used when creating the display. But in my tests, the value of the field is not displaying what I set. What's the proper way to do this?

Here's my code.

function computed_fields_node_view_alter(
		array &$build, 
		Drupal\Core\Entity\EntityInterface $entity, 
		\Drupal\Core\Entity\Display\EntityViewDisplayInterface $display)
{
	if ($display->id() == "node.analysis.default") 
	{			
		/* @var $total Drupal\Core\Field\FieldItemList */
		$total = $entity->field_analysis_total_purchase;
		$total->set(0, "3333");	
	}	
}

Comments

Jaypan’s picture

You can't directly access the field value and set it. You need to get() the value:

$entity->get('field_analysis_total_purchase')->set(0, "3333");