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
Brianna BollettieriBrianna Bollettieri 

Creating an Email Alert off of an Error

I'm trying to create an email alert to be sent based on an error on an opportunity. I created a Unique Name field and workflow off of that which doesn't allow duplicate opportunities to be created. If a duplicate opportunity is created, once you try and save it, there is an error that appears saying that another record already exists (similar to the Duplicate Account rule). So now, I want to create an email alert that is triggered from this opportunity error but I'm not sure how.

Thanks!
RKSalesforceRKSalesforce
Hi Brianna,

This is Doable using before insert trigger and its associated helper class. I am assuming that on the basis of unique field on Opportunity you are deciding duplicate records. I am also assuming that you will send email to Associated Accounts Email address.
Please find below rough code for the same: 
Trigger:
Trigger findDuplicateOpportunities on Opportunity(before insert){
	findDuplicateOpportunitiesHelper helperClass = new findDuplicateOpportunitiesHelper();
	helperClass.processOpportunities(trigger.New);	
}
Helper Class:
public class findDuplicateOpportunitiesHelper{
	public void processOpportunities(List<Opportunity> oppList) {
		Set<String> setOfEmailToSendEmail = New Set<String>();
		Map<String, Opportunity> uniqueFieldAndOpporunityMap = New Map<String, Opportunity>();
        for(Opportunity opp: [Select id, name, Uniquefield from Opportunity ]){
			uniqueFieldAndOpporunityMap.put(opp.Uniquefield, opp);
		}
		for(Opportunity oppt: oppList){
			if(uniqueFieldAndOpporunityMap.containsKey(oppt.Uniquefield)){
				setOfEmailToSendEmail.add(oppt.Account.Email);	
			}
		}
		if(!isEmpty(setOfEmailToSendEmail)){
			//Write your logic to send email
		}
		  
    }
}
Pease mark as best answer if helped.

Regards,
Ramakant
 
Brianna BollettieriBrianna Bollettieri
Hi Ramakant

Okay great, yes the unique field was created to assist with finding duplicate opportunities. I actually want the email to go to the Manager of the person who attempted to create the duplicate record. We have a Manager field on the user screen that could be reference. Would this be possible?

Thanks!
RKSalesforceRKSalesforce
Hi Brianna,

Yes you can do this by using owner id of that Opportunity and then looking for users and their Managers email address.

Regards,
Ramakant