I want to save some details before saving the node, and I tried with hook_node_presave().

function hook_node_presave(Drupal Core Entity EntityInterface $node) {
  if ($node->id() && $node->moderate) {
    // Reset votes when node is updated:
    $node->score = 0;
    $node->users = '';
    $node->votes = 0;

Then with hook_entity_presave().

function hook_entity_presave(Drupal Core Entity EntityInterface $entity) {
  $entity->changed = REQUEST_TIME;

Both hooks don't work. Why?

  • If those are the function names you really used, they aren't considered hooks, except in the case the machine name of the module is hook. – apaderno Dec 19 '16 at 14:27
  • When asking about code you are using, you should show the real code you are using, or it gets harder to answer the question, Also, you could know it, but it would not be the first time users make a typo like that. – apaderno Dec 19 '16 at 15:38

You can do it like this.

function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityType()->id() == 'node') {
    $entity->setTitle('The new Title');
    //CAUTION : Do not save here, because it's automatic.



Your function should be named according to your module's name. If your module is called "foo", then:

function foo_node_presave(Drupal\Core\Entity\EntityInterface $node) {

Note also the use of backslashes, not spaces, to separate namespaces.

  • Yes i have done like that ! – KTM Dec 19 '16 at 14:32
  • @IcecreamJelly I see spaces in the namespace, so the answer given here is correct. If you don't show the code you are using, in a question about code, or the shown code contains typos, don't expect a different answer. – apaderno Dec 19 '16 at 15:40

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