As a Salesforce developer, I am required to add a user to a Sales Team group created in the Salesforce org. However, you only need to add those users with a sales profile.
This is something you need to do programmatically, so here I will explain how to add a user to a group or a permission set using Salesforce Apex.
Add User to Group Using Salesforce Apex
In the image below, you can see the users who are already in the sales group. Now, I want to add a particular user who has been assigned a sales profile to the sales group.

I created a sales profile here, and some users have assigned it. Using the Apex class, we will add any user from these users to the sales group.

Now, I will explain how to fetch details of particular profile users so we can assign them to a sales group.
I created an Apex class named AddUserToGroup and passed the userId variable as a parameter to the method addUserToSalesGroup (Id userId).
- Group Sales Group: The Group is an object present in Salesforce. We can use it as a data type to retrieve details of any particular object. SalesGroup is a variable in which we store the ID of the sales group, and when we define Type=’Regular’, that means we are fetching public group details.
- User user: We fetch user details, such as Profile Name, and then verify if the user is already part of the sales group.
Then, in the if condition, we check that the user profile name we fetched using SOQL equals ‘Sales Profile‘ because we want only sales profile users to add to the sales group.
Next, we need to verify whether the user we want to add to the sales group is already a member. To achieve this, we need to retrieve the details of users already present in the group using the GroupMember object and store them in the List Collection variable.
Then again, using the if condition, we check whether the list is empty. If the list is empty, that means the user we are going to add to the sales group is not already present in the group. If the user is already there, then in the else part, display the message accordingly.
Then, we created a GroupMember object instance called newMember and added our user to the sales group using that instance. Finally, in the try block, we performed the Insert DML operation to save the user to the Salesforce database.
Now, save the apex program, and we need to execute it.
public class AddUserToGroup {
public void addUserToGroup(Id userId) {
Group SalesGroup = [SELECT Id FROM Group WHERE Name = 'Sales Group' AND Type =
'Regular' LIMIT 1];
User user = [SELECT Id, Profile.Name FROM User WHERE Id = :userId LIMIT 1];
if (user.Profile.Name == 'Sales Profile')
{
List<GroupMember> existingGroupMembers = [SELECT Id FROM GroupMember
WHERE GroupId = :SalesGroup.Id AND UserOrGroupId = :user.Id];
if (existingGroupMembers.isEmpty())
{
GroupMember newMember = new GroupMember();
newMember.GroupId = salesGroup.Id;
newMember.UserOrGroupId = user.Id;
try {
insert newMember;
System.debug('User added to the Sales Team group
successfully.');
}
catch (DmlException e) {
System.debug('Error while adding user to the group: ' + e.getMessage());
}
}
else {
System.debug('User is already a member of the Sales Team group.');
}
}
else {
System.debug('User does not have the Sales Profile.');
}
}
}To execute the apex code, open an anonymous window, create an object of the class you created, and call the method you created using the object instance. Here, we need to pass a value to the UserID parameter that we added to the process.
First, I passed the user ID of a user who is not from the sales profile, so that we can check whether the user gets added to the group. Because we only want to add a user who belongs to the sales profile.
Then click the Execute button.

As you can see, the message we passed in the else block is displayed because the user we are adding is not from the sales profile.

Again, I passed the user ID, which was assigned from the sales profile, but that user was already present in the sales group, and again, the else block was executed.

Now, I copied the User ID that belongs to the sales profile, and that user is part of the sales group.

Then, I passed that user ID to the method and executed the code.

You can see the message that we entered in the block where we added users to the group. If users are added, this message is displayed.

Then, as you navigate to the group in the Salesforce org, you will see the user that we added is assigned to the sales group.

In this way, we can add users to the public group using Salesforce Apex.
Add User to Permission Sets Using Salesforce Apex
For example, you created a permission set in Salesforce and now want to add a user to that permission set. Here, I will explain how to add a user to permission sets using Salesforce Apex and also provide the code to do so.
Here, you can see I created a permission set named Employee Permission and added one user whose status is active and who has an employee role.

Now, we will add the user to this permission set. The user must have an active status and be from the ‘employee‘ role. When you try to add an inactive user or other role to the PS, display a message accordingly.
I created a class with the AddUserToPS() method and added the ID and String parameters. Then, using SOQL, I fetched the IDs of the user and permission set objects.
If Condition: We are checking if the user is Active and from the employee profile. If these conditions are met, execute this block; otherwise, the block is executed. In the IF block, we created a list collection variable and used a query to check if the user is already assigned this permission set.
If the list is found empty, we will add the user to this permission set; otherwise, the else block gets executed, which says the user has already been assigned this permission set.
Then, in the Try block, we use the Insert DML operation to assign a permission set, and in the Catch block, we handle any DML exception so that our class executes appropriately.
After that, we save the code and execute it.
public class AddUserToPermissionSet {
public void AddUserToPS(Id UserId, String PermissionsetName){
User user = [Select Id, IsActive, UserRole.Name from User where Id= :UserId Limit 1];
PermissionSet ps = [Select Id from PermissionSet where Name = :PermissionsetName Limit
1];
if ((user.IsActive == True) && (user.UserRole.Name == 'Employee'))
{
List<PermissionSetAssignment> existingAssignments = [SELECT Id FROM PermissionSetAssignment WHERE AssigneeId = :userId AND PermissionSetId = :ps.Id];
if (existingAssignments.isEmpty())
{
PermissionSetAssignment permSetAssignment = new PermissionSetAssignment(
AssigneeId = userId,
PermissionSetId = ps.Id
);
try {
insert permSetAssignment;
System.debug('Permission Set assigned successfully.');
}
catch (DmlException e) {
System.debug('Failed to assign Permission Set: ' + e.getMessage());
}
} else {
System.debug('User already has the permission set.');
}
}
else {
System.debug('Please Check Users Active Status Or User Role.');
}
}
}Next, we need to execute the code for the open anonymous window. This involves creating an object of the class we created and then using an instance of the class to call the AddUserToPS() method, passing the value to the parameter accordingly.
Here, I entered a UserId that has not been assigned an employee role, allowing us to check the output. Then click the Execute button.

Here, you can see that the else block is executed because the criteria we applied to the user do not match this user, and an error message is displayed.

Now, I copied the active user ID from the employee role. Now, we will execute the code with this user ID.

Enter the UserId and Permission Set API name to which you want to add the user. Execute the code.

Now, we have the message permission set assigned successfully, which means the program will be executed successfully.

When you navigate to the permission set from the setup and open the manage assignment, you will see the userID you passed to the Apex code, and the user has been successfully added to the permission set.

In this way, we can add users who meet specific criteria to the permission set using Salesforce Apex.
Conclusion
I hope you have got an idea about adding users to public groups and permission sets using Salesforce Apex. In that, I explained how to add a user to a public group using Salesforce Apex.
In this program, I explained how we can create a method using SOQL query and apply conditions in Apex. Then we saw how to add a user to permission sets using Salesforce Apex so that we can assign the permission sets to the user programmatically.
You may like to read:
- Unable to Activate the Apex Language Server
- Assign Permission Set to New Users Using Salesforce Flow
- How to Find Salesforce Org ID?
- Create a New User Using Salesforce Apex
- Integration License Not Displaying While Creating Integration User in Salesforce
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.