You are here

function userpoints_grant_points in User Points 7.2

Grant a user points.

The function expects three required parameters, an operation string, the amount of points, and the transaction bundle. Optionally, a user id may be passed.

The function then returns a UserpointsTransaction object, which provides methods to add further details to the transaction. New transactions are saved automatically through the __destruct() method. However, if transaction needs to be saved immediately, save() can be called directly.

Basic usage examples:

// Adding points to the current user, relying on automatic saving.
userpoints_grant_points('mymodule_type_action', $points, 'my_userpoints_type');

// Grant points to another, add a entity reference to a node and save
// explicitly.
userpoints_grant_points('mymodule_type_otheraction', $points, 'my_userpoints_type', $account->uid)
  ->setEntity('node', $node->nid)
  ->save();

A list of all available methods can be found in the UserpointsTransaction documentation.

Parameters

$operation: A string that can identify this transaction. Can be used to provide a custom, translatable, optionally dynamic reason for this transaction in transaction listings. See hook_userpoints_info().

$points: A positive or negative point amount that should be assigned to the user.

$type: The userpoints transaction bundle to create. Optional, defaults to the default bundle if it exists.

$uid: UID of the user that should be granted points. Optional, defaults to the current user.

Return value

UserpointsTransaction

Related topics

1 call to userpoints_grant_points()
UserpointsRulesTestCase::testEvents in userpoints_rules/userpoints_rules.test
Test the before and after events and the setter and getter callbacks.

File

./userpoints.module, line 733

Code

function userpoints_grant_points($operation, $points, $type = NULL, $uid = NULL) {
  global $user;
  if (empty($type)) {

    // Default to the default bundle if not set.
    $type = variable_get('userpoints_default_bundle', 'userpoints');
  }
  if (empty($uid)) {

    // Default to the current user if not set.
    $uid = $user->uid;
  }
  try {
    $transaction = new UserpointsTransaction(array(
      'type' => $type,
    ));
  } catch (Exception $e) {
    watchdog_exception('userpoints', $e, 'Unable to create !points transaction.', userpoints_translation());
  }
  return $transaction
    ->setOperation($operation)
    ->setPoints($points)
    ->setUid($uid);
}