function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Yoni LegacyYoni Legacy 

Insert logic to avoid record with duplicate name and owner, but allows duplicate name with different record owner

Hi, 

Can somebody help me with the logic on the following: 

Account List name is existing, but the ownerid is not existing (Different user)  -> insert ok
Account List name is not existing, but owner id is existing in db - insert ok 

Account List name is existing, owner id is existing (Avoid duplicate record with the same Account List name with the same owner)  -> No insert

Basically, I just want to prevent the record to be inserted if the account list name is duplicate and also the same owner, but if the account list has a match in the database, but it's owner is different, it's should be inserted.


Here is my current code: 
 
public with sharing class InsertAccountListRec_TEST_cls {
    
    List<User> usersIdList;
    Set<Id> usersIdSet = new Set<Id>();
    Set<Id> AffFromAcctSet = new Set<Id>();
    Set<Id> xAcctListOidSet = new Set<Id>();
    Set<String> xAcctListNameSet = new Set<String>();
    List<Affiliation_vod__c> allAffParentRecs = new List<Affiliation_vod__c>();
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Account_List_vod__c> xAcctListRecs = new List <Account_List_vod__c>();
    List<Account_List_vod__c> InsertedAccList = new List <Account_List_vod__c>();
    
    
    
    //Creation a list of all Parent Affiliation Records, then add to allParentRecsSet (SET).
    //Start of 1st Block
    public InsertAccountListRec_TEST_cls(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, OwnerId, From_Account_vod__c, From_Account_Value__c, To_Account_vod__c
                                                         FROM Affiliation_vod__c
                                                         WHERE (From_Account_vod__r.Id = '0011200001GNrb0AAD' 
                                                         AND Parent_vod__c = True)
                                                         AND OwnerId IN: getActiveUsers()]);
        
        System.debug('Parent Affiliation Record Count '+ allAffParentRecs.size());
        
        
        for(Account_List_vod__c xAcctListRecs  : [Select OwnerId, Name FROM Account_List_vod__c 
                                                  WHERE Name LIKE 'HO_%'
                                                  AND OwnerId IN: getActiveUsers()]){
                                                                      xAcctListOidSet.add(xAcctListRecs.OwnerId);
                                                      				  xAcctListNameSet.add(xAcctListRecs.Name);
                                                                  }
        
        System.debug('Account List Record Count '+ xAcctListRecs);
        
        for(Affiliation_vod__c allParentAffRecs: allAffParentRecs){
            if(!AffFromAcctSet.contains(allParentAffRecs.From_Account_vod__c)){
                Account_List_vod__c AccListRec = new Account_List_vod__c();    
                AccListRec.Name = 'HO_' + allParentAffRecs.From_Account_Value__c; 
                AccListRec.Icon_Name_vod__c = '0';	
                AccListRec.OwnerId = allParentAffRecs.OwnerId;
                AffFromAcctSet.add(allParentAffRecs.From_Account_vod__c);
                newAccListRecList.add(AccListRec); 
            }
        }
               
         for(Account_List_vod__c acctListToCreate : newAccListRecList){
             if(xAcctListNameSet.contains(acctListToCreate.Name) && !xAcctListOidSet.contains(acctListToCreate.OwnerId)){
                       InsertedAccList.add(acctListToCreate);
             }     
         }	
               
               insert InsertedAccList ;
               System.debug('New Account List Records: ' + InsertedAccList);
	}//end of 1st block
    
    
    public Set<Id> getActiveUsers(){
    
            usersIdList = new List<User>([SELECT Id
                                     FROM User
                                     WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                     OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                     AND IsActive = TRUE]); 
        
            for(User users : usersIdList){
                    usersIdSet.add(users.Id);  
            }
        return usersIdSet;
    }
}// End of Class
The logic which is not working is in line 47 to 51

Thanks for the help..
 
Shailendra Singh ParmarShailendra Singh Parmar
You can do one this to make this logic simple.
  1. Create new external ID field and mark it unique. This field will store AccountName + OwnerID
  2. While you insert record then poluate those values and make upsert call so all new will be inserted and duplicate will be ignored. 
  3. You may have workflow for records being inserted by other system
Other solution you could do is in your apex, create MAP were accountName+ownerID will be key and query all records where account name and ownerID is from new list and put then in map.
In insert list only add elements if combination of name + ownerID is not in map mean they are not inserted only.

Thanks!
Yoni LegacyYoni Legacy
Hi Shailendra,

Thank you for you idea. I'm just very new in apex coding actually this is my first try. I'm still confuse when to use Map or not, or should I say how to use it. If you could give me a sample code of that. I will study it.

Thanks
Marion
Yoni LegacyYoni Legacy
Do you mean to say?
 
map<String, Id> aNameToOwnerIdMap = new map<String,Id>


	for(Account_List_vod__c xAcctListRecs  : [Select OwnerId, Name FROM 						  			     Account_List_vod__c
                                                  WHERE Name LIKE 'HO_%'
                                                  AND OwnerId IN:getActiveUsers()]){
		aNameToOwnerIdMap.put(xAcctListRecs.Name, xAcctListRecs.OwnerId);
	}

I'm not sure what is next if that is right.

Marion
Shailendra Singh ParmarShailendra Singh Parmar
Yes. You could even simply use set like below 
 
Set<String> existingRecords = new Set<String>();
	for(Account_List_vod__c xAcctListRecs  : [Select OwnerId, Name FROM Account_List_vod__c WHERE Name LIKE 'HO_%'AND OwnerId IN getActiveUsers()]){
        existingRecords .add(xAcctListRecs.Name + xAcctListRecs.OwnerId);		
	}

//  add elements in your insert list only if they are not in set
    for(Account_List_vod__c acctListToCreate : newAccListRecList){
             if(!existingRecords.contains(acctListToCreate.Name)){ // Not in list only then insert in new list
                       InsertedAccList.add(acctListToCreate);
             }    
    }

 
Yoni LegacyYoni Legacy
Hi,

I'll try on that and get back to you.

Thanks
Marion
Yoni LegacyYoni Legacy
map<String, Id> aNameToOwnerIdMap = new map<String,Id>


	for(Account_List_vod__c xAcctListRecs  : [Select OwnerId, Name FROM 						  			     Account_List_vod__c
                                                  WHERE Name LIKE 'HO_%'
                                                  AND OwnerId IN:getActiveUsers()]){
		aNameToOwnerIdMap.put(xAcctListRecs.Name, xAcctListRecs.OwnerId);
	}


for(Account_List_vod__c acctListToCreate : newAccListRecList){
         if(!aNameToOwnerIdMap.containsKe(acctListToCreate .Name){
                        InsertedAccList.add(acctListToCreate );
            }
}

so using Map, is the code above is right?
Yoni LegacyYoni Legacy
Hi, 

I tried to use a composite key which will update by Workflow field update after the record was inserted. Here is my code but it's not working.

 
public with sharing class InsertAccountListRec_TEST_cls {
    
    List<User> usersIdList;
    Set<Id> usersIdSet = new Set<Id>();
    Set<Id> AffFromAcctSet = new Set<Id>();
    Set<String> uniqueFieldSet = new Set<String>();
    List<Affiliation_vod__c> allAffParentRecs = new List<Affiliation_vod__c>();
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Account_List_vod__c> xAcctListRecs = new List <Account_List_vod__c>();
    List<Account_List_vod__c> InsertedAccList = new List <Account_List_vod__c>();
    
    public InsertAccountListRec_TEST_cls(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, OwnerId, From_Account_vod__c, From_Account_Value__c, To_Account_vod__c
                                                         FROM Affiliation_vod__c
                                                         WHERE (From_Account_vod__r.Id = '0011200001GNrb0AAD' 
                                                                AND Parent_vod__c = True)
                                                         AND OwnerId IN: getActiveUsers()]);
        
        System.debug('Parent Affiliation Record Count '+ allAffParentRecs.size());
        
        for(Account_List_vod__c xAcctListRecs  : [Select OwnerId, Unique_Owner_Name__c FROM Account_List_vod__c 
                                                  WHERE Name = 'HO_RADY\'S CHILDREN\'S UCSD'
                                                  AND OwnerId IN: getActiveUsers()])
        {
            uniqueFieldSet.add(xAcctListRecs.Unique_Owner_Name__c);
        }
        
        for(Affiliation_vod__c allParentAffRecs: allAffParentRecs){
            if(!AffFromAcctSet.contains(allParentAffRecs.From_Account_vod__c)){
                Account_List_vod__c AccListRec = new Account_List_vod__c();    
                AccListRec.Name = 'HO_' + allParentAffRecs.From_Account_Value__c; 
                AccListRec.Icon_Name_vod__c = '0';	
                AccListRec.OwnerId = allParentAffRecs.OwnerId;
                AffFromAcctSet.add(allParentAffRecs.From_Account_vod__c);
                newAccListRecList.add(AccListRec);
            } 
        }
        
        for(Account_List_vod__c accList : newAccListRecList){
            if(!uniqueFieldSet.contains(accList.Name + accList.OwnerId)){
                InsertedAccList.add(accList);
            }
        }
        
        try{        
            insert InsertedAccList ;
            System.debug('New Account List Records: ' + InsertedAccList);
        }catch(DMLException e){
            System.debug('exeption catch ' + e.getMessage()); 
        }
    }//end of 1st block
    
    
    public Set<Id> getActiveUsers(){
        
        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                      AND IsActive = TRUE]); 
        
        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    }
}// End of Class