Various ways of updating field values in Drupal 8 and 9

A recent tweet by CHX got me thinking. Drupal 8 was released almost 5 years ago, and some things are still a mystery for a lot of developers, including me. Here's the tweet I mentioned:


Just like the majority of people in his poll, I also didn't know that you could shorten this:

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

to this:

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

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

$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 could set the entity object like this:

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

The same also applies if you don't use the set() method:

$entity->field_name = $another_entity;

What about programmatically updating multi-value fields?

The multi-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?

Sure. You can't use the short way 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 price field's property definition 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 have to set the value for both the Number and Currency Code properties. The alternative way to set the multi-property field is like this:

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

And for multivalue fields:

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

About the Author

Goran Nikolovski is an experienced web and AI developer skilled in Drupal, React, and React Native. He founded this website and enjoys sharing his knowledge.