Follow below steps for this Scenario:
Create Domain__c Text Field on Account and Domain__c Formula Text Field on Contact
Formula :
(MID(Email,FIND('@', Email, 1)+1, (LEN(Email) - FIND('@', Email, 1)+1)))
In this scenario Account Domain__c value like ‘gmail.com’ other examples: yahoo.com,wipro.com,infosys.com
Contact Email like ‘salesforcecodes@gmail.com’ then automatically assign Account to this New Contact
trigger AssignAccountToContactBasedOnEmailDomain on Contact (before insert) {
List<String> contactEmaildomains = new List<String>();
for(Contact con : Trigger.new){
contactEmaildomains.add('%'+con.Domain__c+'%');
}
List<Account> accList = [SELECT Id, Domain__c FROM Account WHERE Domain__c
LIKE :contactEmaildomains];
Map<String, Id> domainsMap = new Map<String, Id>();
for(Account a: accList) {
for(String dom : a.Domain__c.Split(','))
domainsMap.put(dom, a.Id);
}
for(Contact c: Trigger.new) {
if(domainsMap.get(c.Domain__c) != null) {
c.AccountId = domainsMap.get(c.Domain__c);
}
}
}
No comments:
Post a Comment