2

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)

1 Answer 1

5

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);
1
  • It works :-) thanks!
    – cocq
    Sep 13, 2021 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.