Score:0

How can I programmatically delete a field value?

gb flag

Using Entity API, I know how to get a value or to set a value :

$nid = $entity->id();
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
...
$nom = strtoupper($node->get('field_nom')->value);
$node->set('field_nom', $nom);
$node->save();

But is there a possibility to delete a value of this field?

I tried to directly delete the value in the database

$query =\Drupal::database()->delete('node__field_nom');
$query->condition('field_nom', $nom);
$query->execute();

But since the value is cached, the node have to reload twice to see the result on the screen (an empty field)

Score:2
cn flag

The field content is a field item list and normally you would need to include a single value also in an array. The fact that you can set a scalar like in your example is due to extra code in the Field API detecting the scalar and transferring it to a field item list with a single value. To delete the field you can't set an empty scalar, though, because this would be interpreted as a single field item with that empty value.

So to delete the entire field content set an empty array:

$node->set('field_nom', []);

BTW you can get the entire field content:

$values = $node->get('field_nom')->getValue();

Change the array $values and set it again:

$node->set('field_nom', $values);
cocq avatar
gb flag
It works :-) thanks!
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.