Updating field values in Drupal 8 and 9

When you have to modify the values of the fields by code, there are several ways to do it. The most typical one:

$entity->field_name->value = 'foo' 
$entity->field_name->target_id = 123

but it is the same as doing:

$entity->field_name = 'foo' 
$entity->field_name = 123

That's a shorter way to write the same thing, which is good, but personally I prefer to use the set() method this way:

$entity->set('field_name', 'foo'); 
$entity->set('field_name', 123);

Somehow, this looks and feels much better in my opinion. It's worth mentioning that for entity reference fields instead of the entity ID, you can set the entity object this way:

$entity->set('field_name', $another_entity);

The same also applies if you do not use the set() method:

$entity->field_name = $another_entity;

What about multi-value fields?

Multiple value fields are no different. You just have to use arrays. So, instead of this:

$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];

you can use this:

$entity->field_name_muti = ['foo', 'bar', 'baz']; 
$entity->field_name_multi = [1, 2, 3];
$entity->field_name_multi = [$another_entity1, $another_entity2, $another_entity3];

Are there any exceptions?

Yes. You cannot use the shortcut if you have a field type with multiple properties. For example, the Price field in Drupal Commerce has more than one property. You can see the property definition of the price field here . To set the value of a price field, you can do this:

$entity->field_price->number = 10; 
$entity->field_price->currency_code = 'EUR';

In this case, you must set the value for the Number and Currency code properties. The alternative way to set the multiple property field is as follows:

$entity->field_price = ['number' => 99, 'currency_code' => 'EUR'];

And for multi-value fields:

$entity->field_prices = [
  ['number' => 10, 'currency_code' => 'EUR'],
  ['number' => 99, 'currency_code' => 'EUR'],

Have Any Project in Mind?

If you want to do something in Drupal maybe you can hire me.

Either for consulting, development or maintenance of Drupal websites.