3

How know inside hook_entity_presave() if the entity is create or update please ? Thanks.

Note: I want use presave and not update and insert hook.

3 Answers 3

12

Like this:

if ($node->isNew()) {

}

Note that this only works before saving, in insert/update, it will always return TRUE, because the node has already been saved and is no longer new.

0

In addition to the above answer, you also could check

if (!empty($node->nid)) {

}
1
  • 2
    No, that is not correct like this. This specific code snippet is always true in 8.x because $node->nid is an object. $node->nid->value or just !$node->id() would work, except in special cases when saving a new node with a predefined ID (e.g. migrations). isNew() also also much more self-speaking than that check.
    – Berdir
    Feb 1, 2015 at 20:15
0

An updated entity will always contain a copy of the original entity:

if (isset($entity->original)) {

}

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.