Score:0

Statistics counter based on user role

do flag

I need to track some basic usage statistics for a subset of my authenticated user roles in Drupal 9.

Is there a way to make the core statistics counter only count node views based on user roles? The three counters it provides are all I need, I just need them to only record certain user roles.

Score:2
cn flag

The statistics module adds a js library to the node build. You can remove it if you don't want to count the node:

mymodule.module

/**
 * Implements hook_ENTITY_TYPE_view_alter() for node entities.
 */
function mymodule_node_view_alter(array &$build) {
  $roles = \Drupal::currentUser()->getRoles();
  if (!in_array('special_role', $roles)) {
    if (isset($build['#attached']['library'])) {
      $key = array_search('statistics/drupal.statistics', $build['#attached']['library']);
      if ($key !== FALSE) {
        unset($build['#attached']['library'][$key]);
      }
    }
  }
}

This only works if the roles are altering permissions. If not, add a cache context for the user roles:

$build['#cache']['contexts'][] = 'user.roles';
do flag
That looks perfect thank you. I'm afraid I don't understand this line though `This only works if the roles are altering permissions.` could you explain what you mean by that?
4uk4 avatar
cn flag
Normally every role has a different set of permissions. But you could create multiple roles with the same permissions and then use them to control things not directly connected to permissions, like here.
do flag
Sorry, I'm even more confused now. The snippet makes sense; it removes the statistics js library if the user doesn't have the correct role. Why does the cache context matter here? I don't plan on changing user roles, Or is the same modified node getting presented to multiple users?
4uk4 avatar
cn flag
Yes, exactly. By default, the cached node is presented to any user having the same permissions.
do flag
That is somewhat counter-intuitive to me but does explain some odd behavior with user roles I've run into before...
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.