Information for: DEVELOPERS   PARTNERS

Block users based on a certain criteria

Fast Track to Drupal 8 Coding – Back to intro
Previous lesson - Update users programmatically
Next lesson – Define a custom config entity

Lesson Goal

Block users who have not signed in for the last six months.

Implementation Method

Drupal Version Method
Drupal 7 Use hook_cron with user_user_operations_block()
Drupal 8 Use hook_cron with User::block

Drupal 7 method

  1. Add the following code to the lotus.module file:

      function lotus_cron() {
        $results = db_select('users', 'u')
                    ->fields('u', array('uid'))
                    ->condition('login', strtotime('-6 months'), '<=')
                    ->execute();
        foreach ($results as $result) {
          $uids[] = $result->uid;
        }
        if (!empty($uids)) {
          $users = user_load_multiple($uids);
          user_user_operations_block($users);
        }
    }
    
  2. Run cron.

Drupal 8 method

  1. Add the following code to the lotus.module file:

    function lotus_cron() {
      $result = \Drupal::entityQuery("user")
        ->condition('login', strtotime('-6 months'), '<=')
        ->execute();
    
      $storage_handler = \Drupal::entityTypeManager()->getStorage("user");
    
      foreach ($result AS $user) {
        $entity = $storage_handler->load($user);
        $entity->block();
        $storage_handler->save($entity);
      }
    }
    
  2. Run cron.

Resources

User::block