Implementing hook_flag_access for Controlling What the User Can Flag

2011-02-23

Jitesh Doshi

Implementing hook_flag_access for Controlling What the User Can Flag

How to limit users to flag only one node at a time using hook_flag_access in Drupal.

Recently, a client wanted their site users to be able to show their support for certain content nodes in Drupal. This can be done very nicely with the flag module.

But the client requirement was that a user should not be able to support more than one node at a time. That means we have to implement an upper limit of 1 on the number of nodes a user can support.

The 2.x version of the flag module provides a special hook called hook_flag_access that can help implement this feature:

function MYMODULE_flag_access($flag, $content_id, $action, $account) {
  if($flag->name == 'membersupport' && $action == 'flag') {
    if($flag->get_user_count($GLOBALS['user']->uid) > 0) {
      return FALSE;
    }
  }
}

In the code above, when the flag being flagged is a certain one (‘membersupport’) and the action is ‘flag’, we check the number of nodes this user has already flagged with the same flag. If that number is greater than zero, then they are not allowed to flag any more.