You are here

function user_badges_user_save in User Badges 5

Same name and namespace in other branches
  1. 6.2 user_badges.module \user_badges_user_save()
  2. 6 user_badges.module \user_badges_user_save()
  3. 7 user_badges.module \user_badges_user_save()
  4. 7.2 user_badges.module \user_badges_user_save()
  5. 7.3 user_badges.module \user_badges_user_save()

Assign user badges to a user

Parameters

$edit is an array containing badges array:

$uid is the user id:

$quiet suppresses message display:

1 call to user_badges_user_save()
user_badges_page_form_submit in ./user_badges.module

File

./user_badges.module, line 280
@brief User Badges module file

Code

function user_badges_user_save($edit, $uid, $quiet = TRUE) {
  $badges = user_badges_get_badges($uid);
  if (is_array($edit)) {

    // an array of just the checked boxes please
    $newbadges = array();
    foreach ($edit as $bid => $is_selected) {
      if ($is_selected) {
        $newbadges[] = $bid;
      }
    }
    $success = TRUE;

    // what are the added badges?
    $added = array_diff($newbadges, array_keys($badges));
    foreach ($added as $bid) {
      if (!key_exists($bid, $badges)) {
        $success = (bool) user_badges_user_add_badge($uid, $bid);
      }
    }

    // what are the removed badges?
    $removed = array_diff(array_keys($badges), $newbadges);
    foreach ($removed as $bid) {

      // and user has this badge
      if (key_exists($bid, $badges)) {
        $success = $success && (bool) user_badges_user_remove_badge($uid, $bid);
      }
    }
    if ($success && !$quiet) {
      drupal_set_message(t('Badges saved.'));
    }
    elseif (!$quiet) {
      drupal_set_message(t('There was a problem saving badges to the database.'));
    }
  }
}