1

I'm trying to record the user agent string into a text field (field_useragent) the first time a content type is saved. This is what I tried:

/*
 * Implements hook_ENTITY_TYPE_insert()
 */
function mymodule_node_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'my_content_type') {
    // Log the user agent.
    $entity->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
  }
}

But, this doesn't save the user agent string. So I tried using this code:

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'my_content_type') {
    // Log the user agent.
    $entity->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);  }
}

This saves the user agent string, but it does so every time the node is edited. How can I save it only upon insertion?

5
  • Have you tried to check, if the node id isset? I think the first time there will be no node id.
    – sgoelz
    Feb 3, 2016 at 10:30
  • 3
    In the second case use $entity->isNew(). In the insert the documentation says "This hook runs once the entity has been stored.". So you're too late :)
    – user21641
    Feb 3, 2016 at 11:11
  • Have you tried reacting to a "rule" when the content is saved?
    – rrirower
    Feb 3, 2016 at 14:25
  • @rrirower Alas, rules is unstable for D8 at this time. Feb 3, 2016 at 15:19
  • 1
    See documentation for hook_ENTITY_TYPE_insert(). When using hook_entity_insert, the entity is already saved. This is why your update didn't seem to work. If you want to set a value on the entity, you'd need re-save the entity after setting, e.g. call $entity->save();.
    – sonfd
    Dec 19, 2019 at 3:40

1 Answer 1

1

As per @Ivan Jaros comment:

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'my_content_type') {
    /// Log the user agent if the account is being created.
    if ($entity->isNew()) {
      $entity->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
    }
  }
}

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.