Get Current User Last Access Timestamp Per Node in HOOK_preprocess_node()

2018-10-18 07:22:28

Drupal 8.x

I am trying to compare the current users last access timestamp to other timestamp values and am wondering how to get the current users "last_access" in HOOK_preprocess_node().

MYMODULE.module:

function MYMODULE_preprocess_node(&$variables) {

kpr(\Drupal::currentUser()->getLastAccessedTime());

}

This returns a timestamp, however it updates quite infrequently and not on node load, or even after cache clear, and does not seem node specific.

I've accessed this value in HOOK_preprocess_user() with $variables['elements']['#user']->access->value, however, I would like the same value available in node.

How do you get the timestamp of the users last view of a node per node?

This doesn't work because the node is cached. Disabling caching of the node wouldn't be a good idea performance-wise. Try instead a lazy builder to retrieve the access time and create a placeholder in the node, so that the node can be cached no matter how often the access time is u

  • This doesn't work because the node is cached. Disabling caching of the node wouldn't be a good idea performance-wise. Try instead a lazy builder to retrieve the access time and create a placeholder in the node, so that the node can be cached no matter how often the access time is updated:

    /**

    * Implements hook_preprocess_HOOK() for node templates.

    */

    function mymodule_preprocess_node(&$variables) {

    $variables['content']['timestamp'] = [

    '#lazy_builder' => ['mymodule_timestamp_current_user', []],

    '#create_placeholder' => TRUE,

    ];

    }

    /**

    * #lazy_builder callback; builds timestamp markup with current user access time.

    */

    function mymodule_timestamp_current_user() {

    $timestamp = \Drupal::currentUser()->getLastAccessedTime();

    return [

    '#markup' => $timestamp,

    '#cache' => ['max-age' => 0],

    ];

    }

    2018-10-18 08:33:16