Working with multiple values
This example shows how to set and display multiple values for a computed field.
to populate a multi-valued field, a single value must still be returned, but your function will be called multiple times for each of your values (or "deltas").
So it's necessary to populate the full delta-keyed array, but then only return the value requested (for each delta).
function computed_field_FIELD_NAME_compute($entity_type_manager, $entity, $fields, $delta) {
// Fill in array values with data. The keys are optional in this case as they are the defaults.
$values = [
0 => 'Dog',
1 => 'Cat',
2 => 'Mouse',
];
// Return the single value currently requested by the system.
return $values[$delta];
}
getting the value/values
when having single value field this line will return the single value:
$val = $node->your-field-item->getValue();
but if you having a multi-value field, the same line will return an array:
To get all values of a multi-value field:
$node = $variables['node'];
$values = array();
foreach ($node->field_name->getValue() as $value) {
if (!empty($value['value'])) {
$values[] = $value['value'];
}
}
or
$node = $variables['node'];
$values = array();
foreach ($node->field_name as $item) {
if (!empty($item->value)) {
$values[] = $item->value;
}
}
setting the multi value field:
$node->field_name[LANGUAGE_NONE][] = new_value;
More shortcuts and ways to update multi-value field programmatically
$entity->field_name_muti->value = ['foo', 'bar', 'baz'];
$entity->field_name_multi->target_id = [1, 2, 3]
$entity->field_name_multi->target_id = [$another_entity1, $another_entity2, $another_entity3]
this will also work:
$entity->field_name_muti = ['foo', 'bar', 'baz'];
$entity->field_name_multi = [1, 2, 3]
$entity->field_name_multi = [$another_entity1, $another_entity2, $another_entity3]