/** * Update role of user * @param int $newRoles $newRoles has form Array([11] => 1, [12] => 0, ..., [n] => m)) with n is role ID and m is checked/unchecked * @param int $userID * @return bool */ public function updateRolesOfUser($roleIDs, $userID) { // get old roles $oldRoles = $this->getRolesOfUser($userID); // extract old role ID except "customer role ID" $roleModel = new Admin_Model_Role(); $customerRoleID = $roleModel->getCustomerRoleID(); $oldRoleIDs = array(); foreach ($oldRoles as $oldRole) { if ($oldRole['role_id'] != $customerRoleID) { $oldRoleIDs[] = $oldRole['role_id']; } } // assign $roleIDs to $newRoleIDs; $newRoleIDs = $roleIDs; $db = Zend_Db_Table::getDefaultAdapter(); $db->beginTransaction(); try { // following the algorithm, we have oldRoleIDs as A, newRoleIDs as B foreach ($oldRoleIDs as $index => $id) { if (!in_array($id, $newRoleIDs)) { $this->deleteRoleOfUser($id, $userID); unset($oldRoleIDs[$index]); } } foreach ($newRoleIDs as $id) { if (!in_array($id, $oldRoleIDs)) { $this->insertRoleOfUser($id, $userID); } } $db->commit(); return true; } catch (Zend_Exception $e) { $db->rollBack(); return false; } }
/** * Create checkboxes for updating user * @param int $userID * @return array */ private function _createCheckboxesForUpdatingUser($userID) { $roleCheckboxes = array(); // get role array $roleModel = new Admin_Model_Role(); $roleArray = $roleModel->getRoleArray(); // get customer role ID $customerRoleID = $roleModel->getCustomerRoleID(); // get roles of the user $userModel = new Admin_Model_Users(); $rolesOfUser = $userModel->getRolesOfUser($userID); // extract role_id of $roleOfUser array $roleIDs = array(); foreach ($rolesOfUser as $role) { $roleIDs[] = $role['role_id']; } // create role checkboxes foreach ($roleArray as $index => $role) { if (in_array($role['role_id'], $roleIDs)) { $roleCheckbox = $this->createElement('checkbox', (string) $role['role_id'], array('checked' => 'checked')); } else { $roleCheckbox = $this->createElement('checkbox', (string) $role['role_id'], array()); } // check if the role is customer if ($role['role_id'] == $customerRoleID) { $roleCheckbox->setAttrib('disabled', 'disabled'); } $roleCheckbox->setLabel($role['role_name']); $this->_customizeRoleCheckBox($roleCheckbox); $roleCheckboxes[] = $roleCheckbox; } return $roleCheckboxes; }