0

I am working on apex sharing and having trouble making it so only a single share record is allowed per Team Member. enter image description here Here you can see there are 2 of the exact same Team Members with varying access levels. The sharing record seems to just take the latest one, to avoid this I want my code to only allow unique Team Member User Ids to be added. Here is my TriggerHandler Class, I created a Set to store userIds but I'm still able to add duplicate users on the front end.

public class SOTeamMemberTriggerHandler {

public void callCreateSharesHelper(List<Strategic_Opportunity_Team_Member__c> teamMembers) {
     
    TeamSharingHelper helper = new TeamSharingHelper();
    for (Strategic_Opportunity_Team_Member__c tm : teamMembers) {
        Set<Id> userIds = new Set<Id>();
        if (!userIds.contains(tm.User__c)) {
            if (tm.Access_Level__c != 'None') { 
                Map<Id, String> userIdToAccessLevel = new Map<Id, String> { tm.User__c => tm.Access_Level__c };
                    helper.createShares(
                        tm.Strategic_Opportunity__c, 
                        Schema.Strategic_Opportunity__Share.SObjectType, 
                        Schema.Strategic_Opportunity__Share.rowCause.Strategic_Opportunity_Team__c, 
                        userIdToAccessLevel
                    );
            } 
        }
        userIds.add(tm.User__c);

    } 
}
}

What am I missing? Thanks in advance!

1 Answer 1

0

You are initializing new Set inside the loop so it is essentially empty for each user. Move creating set outside of loop

Change

    TeamSharingHelper helper = new TeamSharingHelper();
    for (Strategic_Opportunity_Team_Member__c tm : teamMembers) {
        Set<Id> userIds = new Set<Id>();

to

    TeamSharingHelper helper = new TeamSharingHelper();
    Set<Id> userIds = new Set<Id>();
    for (Strategic_Opportunity_Team_Member__c tm : teamMembers) {

3
  • i moved this but unfortunately i'm still able to add the same user multiple times
    – user92335
    Mar 9, 2022 at 20:12
  • Note that if you are trying to add same user across different txn, then it wont prevent. To do that, you need to query existing records and initialize the set and then loop through new records.
    – metasync
    Mar 9, 2022 at 21:46
  • yes i want it to prevent across different transactions. is this even possible with an after trigger? i was testing a few things but everytime the set would never be empty because it would add the value im currently working on
    – user92335
    Mar 10, 2022 at 16:08

You must log in to answer this question.