0

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?

1
  • 2
    Try var_dump($entity->toArray()); instead of dumping the object. If you want to investigate the object then use xdebug and set a breakpoint.
    – 4uk4
    Dec 15, 2017 at 20:53

1 Answer 1

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.
}

Your Answer

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

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