1

I created a TWIG template for the "Teaser" view of the user account.

I want to display a logo and change its color according to the status of the user :

  • When the user is logged in <i class="user-online fa fa-circle fa-lg"></i> Online

  • When the user is logged in and the last access is less than 30 minutes <i class="user-absent fa fa-circle fa-lg"></i> Absent

  • When the user is offline <i class="user-offline fa fa-circle fa-lg"></i> Offline

How to display the status of the user ?

I think it must be possible to create conditions in TWIG

2

you can use template_preprocess_user like


 /**
 * Implements hook_entity_presave().
 */
function mytemplate_preprocess_user(&$variables) {
  // get user object
  $user = $variables['elements']['#user'];
  //- The user has logged in at least once
  if ($user->getLastLoginTime()) {
    if (account_is_logged_in_less_then_thirty_minutes($user->id())) {
      $status = 'Online';
    }
    else {
      $status = 'Absent';
    }
  }
  else {
    $status = 'offline';
  }
  $variables['status'] = $status;
}

/**
 * @param $uid
 *
 * @return bool
 */
function account_is_logged_in_less_then_thirty_minutes($uid) {
  $connection = Database::getConnection();
  $query = $connection->select('sessions', 'sessions')
    ->fields('sessions', ['sid', 'uid', 'timestamp'])
    ->condition('sessions.uid', $uid, '=')
    //- chef if the user was online in 30 minutes (60 * 30)
    ->condition('sessions.timestamp', \Drupal::time()
        ->getRequestTime() - (60 * 30), '>')
    ->execute();
  //- Get result.
  $results = $query->fetchAll(\PDO::FETCH_OBJ);
  return (count($results) > 0) ? TRUE : FALSE;
}

In you template check on status variable like the following:

{% if status == 'Online' %}
  <i class="user-online fa fa-circle fa-lg"></i> Online
{% elseif status == 'Absent' %}
  <i class="user-absent fa fa-circle fa-lg"></i> Absent
{% else %}
  <i class="user-offline fa fa-circle fa-lg"></i> Offline
{% endif %}

Add use Drupal\Core\Database\Database; to the top of your file.

4
  • I found another question, but I do not want to use views drupal.stackexchange.com/questions/241342/…
    – user90818
    Nov 30 '18 at 18:32
  • This person deleted their account or comments and it’s confusing to follow.
    – Kevin
    Dec 4 '18 at 13:56
  • yeah i think, i edit my answer because, the same person with another account post this question again
    – berramou
    Dec 4 '18 at 14:15
  • stackoverflow.com/questions/53603276/… There is another problem with this code. Now offline users are marked as absent
    – user90903
    Dec 4 '18 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy