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
sfdeveloper12sfdeveloper12 

Trigger to delete share if account owner and custom account owner is same user

Hello, 

I am writting a trigger where i am using salesforce standard account owner field and custom account owner field. Both field have lookup to get USER.
I wrote "Account Share" trigger when we change any account owner then all the data transfer to the new account owner and  data assigned to old account owner gets deleted. But when this two that means standard and custom account owner is same then it throws an error "Delete_Share: execution of BeforeUpdate caused by: System.DmlException: Delete failed. First exception on row 0 with id 00r28000020WLxjAAG; first error: DELETE_FAILED, cannot delete owner or rule share rows, id=00r28000020WLxj: [] Trigger.Delete_Share: line 33, column 1". Please tell me what to over here.

trigger Delete_Share on Account (before update) {


set<Id> AccountIDs = new Set<Id>();
for(Account a: trigger.new){
AccountIDs.add(a.id);
}
List<AccountShare> jobShares = new List<AccountShare>();

map<String,AccountShare>accountShareMap = new Map<String,AccountShare>();

for(AccountShare accShare : [select AccountId, UserOrGroupId from AccountShare where AccountId in :AccountIds])
{
 accountShareMap.put(String.valueOf(accShare.UserOrGroupId),accShare);

}


for(Account a : trigger.new){
Account oldAccount = Trigger.OldMap.get(a.id);
if (a.owner1__c != null) {
 
   AccountShare accountRecord = accountShareMap.get(string.valueOf(oldAccount.owner1__c));
    if (accountRecord  != null)
    jobShares.add(accountRecord);
  }
 }
for(Account a1 : trigger.new){
Account oldAccount = Trigger.OldMap.get(a1.id);
if(jobShares.isEmpty() == false  && a1.owner1__c == a1.OwnerID){
//if(jobShares.isEmpty() == false ){

 delete jobShares;
 }
}
}

Thanks & Regards,
Utkarsha