Manipulating entities

Now that we know how we can read field data programmatically, let's see how we can change this data and persist it to the storage. So, let's look at the same Node title field and update its value programmatically.

The most common way you can change a field value on a content entity is this:

$node->set('title', 'new title');

This works well with fields that have only one value (cardinality == 1) and behind the scenes essentially this happens:

$node->get('title')->setValue('new title');

This one value gets transformed into a raw array of one value because we are dealing with a list of items and the first item receives the changed value. If the field has a higher cardinality and we pass only one value as such, we essentially ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.