Quick Summary on Logic:
The below trigger written in Lead object using equals and hashCode Method. This methods are used on uniqueness. Each hashCode value is unique.
For example: test@mail.com and Test@mail.com will provide different hashCode values.
Object: Lead
Logic: If Lead record contains same Email and Company Name, then the below trigger will prevent duplication.
Apex Class
- public class DeDupeWrapper
- {
- public String email;
- public String company;
- public DeDupeWrapper(String email, String company)
- {
- this.email = email != null ? email.toLowerCase() : email;
- this.company = company != null ? company.toLowerCase() : company;
- }
- public Boolean equals(Object obj)
- {
- if (obj instanceof DeDupeWrapper)
- {
- DeDupeWrapper p = (DeDupeWrapper)obj;
- return ((email == p.email) && (company == p.company));
- }
- return false;
- }
- public Integer hashCode()
- {
- return (email.hashCode() * company.hashCode());
- }
- }
Apex Trigger
- trigger DeDuplicateLead on Lead(before insert, before update)
- {
- Map<DeDupeWrapper, Lead> leadMap = new Map<DeDupeWrapper, Lead>();
- Map<String, String> duplicateMap = new Map<String, String>();
- for (Lead currLead: Trigger.new)
- {
- if((Trigger.isInsert && (currLead.Email != null && currLead.company != null)) ||
- (Trigger.isUpdate && (currLead.Email != Trigger.oldMap.get(currLead.Id).Email ||
- currLead.Company != Trigger.oldMap.get(currLead.Id).Company)))
- {
- DeDupeWrapper key = new DeDupeWrapper(currLead.Email, currLead.Company);
- if (leadMap.containsKey(key))
- {
- currLead.Email.addError('DUPLICATE CAUGHT...!');
- }
- else
- {
- leadMap.put(key, currLead);
- }
- }
- }
- for(DeDupeWrapper currWrap : leadMap.keySet())
- {
- duplicateMap.put(currWrap.Email, currWrap.company);
- }
- for (Lead lead : [SELECT Email,Company FROM Lead WHERE Email in: duplicateMap.keySet() AND Company in: duplicateMap.values()])
- {
- DeDupeWrapper key = new DeDupeWrapper(lead.Email, lead.Company);
- Lead newLead = leadMap.get(key);
- if(newLead != null)
- {
- newLead.addError('DUPLICATE RECORD ALREADY FOUND');
- }
- }
- }
No comments:
Post a Comment