Inserting in user's field on creating the user? I need to add subscription key field to user as a hash of his email and time created so I did this in a custom module

function custom_newsletter_mail_entity_presave($entity, $type) {

    if($type == 'user') {
        if(empty($entity-&gt;get('field_subscription_key')-&gt;getValue()[0]['value'])) {
            $hash_input = $entity-&gt;getEmail() . $entity-&gt;getCreatedTime();
            $key = hash ('sha256' , $hash_input , FALSE);
            $entity-&gt;set('field_subscription_key',$key);
            // $entity-&gt;save();
        }
    }
}


This is not working for some reason, note that I tried this outside of module on all users array and it worked. for some reason, the subscription key field is still empty, the second if condition is there to prevent the field from being overwritten.
If you're using Drupal 8,
See This one.

Update a node:

Example 1 : Update title

$node = \Drupal\node\Entity\Node::load($nid);
$node-&gt;setTitle('The new Title')
$node-&gt;save();


Example 2 : Update a field ('body' and 'field_name')

$node = \Drupal\node\Entity\Node::load($nid);
$node-&gt;set("body", 'New body text');
$node-&gt;set("field_name", 'New value');
$node-&gt;save();


To make changes after click on save / edit button, you can use the hook_entity_presave.
hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity);

Example:

function CUSTOM_MODULE_node_presave(Drupal\node\NodeInterface $node) {
  $node-&gt;setTitle('Edited Title');
  $node-&gt;set('body', 'this is the bew body');
  //CAUTION : Do not save here, because it's automatic.
}



  Note : Do not re save inside of hook_entity_presave().


Using HOOK_entity_presave()

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


Source : drupal8.ovh