0

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->get('field_subscription_key')->getValue()[0]['value'])) {
            $hash_input = $entity->getEmail() . $entity->getCreatedTime();
            $key = hash ('sha256' , $hash_input , FALSE);
            $entity->set('field_subscription_key',$key);
            // $entity->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.

1 Answer 1

1

If you're using Drupal 8, See This one.

Update a node:

Example 1 : Update title

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

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

$node = \Drupal\node\Entity\Node::load($nid);
$node->set("body", 'New body text');
$node->set("field_name", 'New value');
$node->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->setTitle('Edited Title');
  $node->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->getEntityType()->id() == 'node') {
    $entity->setTitle('The new Title');
    //CAUTION : Do not save here, because it's automatic.
  }
}

Source : drupal8.ovh

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.