HOOK_entity_presave: field not accessible

by Larzan   Last Updated December 15, 2017 20:07 PM

I have been brooding on this problem for a while now and i can't figure it out:

I am trying to retrieve and finally modify two values of my entity. With the first one (field_registro) it works, with the second one (field_final_note) it doesn't.

Both fields are of type Number (integer) with no restrictions.

This is how my hook looks like:

function mymodule_entity_presave(\Drupal\Core\Entity\EntityInterface $entity) {
  var_dump($entity->field_registro); // works
  var_dump($entity->field_final_note‎); // NULL
}

When i dump the whole entity i can see both fields (the second one should be empty and be set programatically, the first one has a user value).

See the dump here: https://pastebin.com/wcpyDt9h

I can see that there is clearly a difference in the structure, but i can't figure out WHY and HOW to fix it.

Can anybody point me in the right direction please?

Tags : 8 entities hooks


Answers 1


Since Drupal 8 you need use OOP methods to get value from an entity field. For example:

// If you have a field with machine name "field_final_note‎".
$values = $entity->get('field_final_note‎')->getValue();

Also, have a look for the type of the entity:

if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'node_type') {
 // Your code.
}

P.S. Well it is very helpful to know the next points

// An old entity state.
if (isset($entity->original)) {
  $old_entity = $entity->original;
  // Some code.
}    

// If the entity is new.
if ($entity->isNew()) {
  // Some code.
}
slivorezka
slivorezka
December 16, 2017 16:46 PM

Related Questions


Insert data into entity programmatically

Updated May 16, 2017 17:07 PM

How to create edit custom url for entity

Updated July 10, 2017 08:07 AM


How to get nid while inserting new node drupal 8

Updated January 04, 2018 13:07 PM