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.
By randalx on
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
You can't directly access the
You can't directly access the field value and set it. You need to get() the value: