Unblock users with Views Bulk Operations (VBO) in Drupal 7

Unblock users with Views Bulk Operations (VBO) in Drupal 7
Posted by Gulab Bisht

Views Bulk Operations (VBO) module in Drupal development allows developers to add 'bulk operation' option in views. With this bulk operation option, users can select multiple items and perform actions on them, such as 'delete item', 'publish content' and 'unpublish content'.

Actions provided by Views Bulk Operations module depends on the content on which the bulk operation is to be performed. While creating the user's list in views, Views Bulk Operations (VBO) module gives the option to perform 'Block current users' operation but doesn't give any option to perform 'Unblock current user' operation.

To add this operation, we can use hook_action_info() function. This function declares information about the action and calls another function which performs the action. Below is the code to add 'Unblock the user' option in Views Bulk Operations field.

/**
* Implements hook_action_info().
*/
function mymodule_action_info() {
  return array(
    'mymodule_unblock_user_action' => array(
      'label' => t('Unblock the user'),
      'type' => 'user',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}

/**
* Unblocks a user, defaulting to the current user.
*
* @ingroup actions
*/
function mymodule_unblock_user_action(&$entity, $context = array()) {
  // First priority: If there is a $entity->uid, unblock that user.
  // This is most likely a user object or the author if a node or comment.
  if (isset($entity->uid)) {
    $uid = $entity->uid;
  }
  // Otherwise get user ID from the context.
  elseif (isset($context['uid'])) {
    $uid = $context['uid'];
  }
  $account = user_load($uid);
  $account = user_save($account, array('status' => 1));
  watchdog('action', 'Unblocked user %name.', array('%name' => $account->name));
}

hook_action_info() function returns an array of the function containing a code which will be executed on the items selected in the view. After performing the action, we log an entry in watchdog with watchdog() function to ensure that we have the log entry for the action performed.

With hook_action_info() function, we can create other custom operations as well, to perform on multiple items in Bulk Operations Field.