Skip to content

Instantly share code, notes, and snippets.

@renatoliveira
Last active April 26, 2019 19:25
Show Gist options
  • Save renatoliveira/d107f9dc6a78193e3e32f528f61f213d to your computer and use it in GitHub Desktop.
Save renatoliveira/d107f9dc6a78193e3e32f528f61f213d to your computer and use it in GitHub Desktop.
Assigns a permission "PermissionName" to users from profiles that were specified.
// Permission set's name that I want to assign to all the users
String psName = 'PermissionName';
// Query the permission set
PermissionSet ps = [
SELECT
Id,
Label,
Name
FROM PermissionSet
WHERE IsCustom = TRUE // might want to remove this if you want to assign a standard permission set
AND Name = :psName
];
// build a new list with the name of the profiles you want to assign this permission to
List<String> profiles = new List<String>();
// add more lines as needed, with the EXACT profile name
profiles.add('The profile name');
// we proceed to query the users that do not have the permission set
List<User> users = [
SELECT
Id
FROM User
WHERE Profile.Name IN :profiles
AND IsActive = TRUE
AND Id NOT IN (
SELECT
AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSetId = :ps.Id
)
];
System.debug('Users: ' + users.size());
List<PermissionSetAssignment> assignments = new List<PermissionSetAssignment>();
// for each user we create a new assignment
for (User u : users) {
PermissionSetAssignment psa = new PermissionSetAssignment();
psa.AssigneeId = u.Id;
psa.PermissionSetId = ps.Id;
assignments.add(psa);
}
// and we insert those assignments to the database
List<Database.SaveResult> results = Database.insert(assignments, false);
// display error messages if there's an error
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
System.debug(LoggingLevel.ERROR, sr);
System.debug(LoggingLevel.ERROR, sr.getErrors());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment