You need to sign in to do that
Don't have an account?
DeveloperSalesforce
Trigger on Contact (before insert)
Hi,
I have requirement here:
When XYZ contact is created, check if a XYZ Company with exact Company Name field on Account exists.
If exists, link contact to the account. If Company does not exist, then create a new XYZ Account and set owner.
trigger TriggerContactInsert on Contact (before insert) {
List<String> cntCompName = new List<String>();
for(Contact xcnt: trigger.new)
{
cntCompName.add(xcnt.Company_Name__c);
}
list<Account> acctLst = [select Id, Name,(select Company_Name__c from Contacts) from Account where Name IN :cntCompName];
system.debug('Account' + acctLst);
Map<id,List<Contact>> mapofCmpNames = new Map<id,List<Contact>>();
for(Account l : acctlst)
{
for(List<Contact> e : l.Contacts)
{
mapofCmpNames.put(l.id, e);
}
}
for(Contact xcnt: trigger.new)
{
List<Contact> existingCmp = mapofCmpNames.get(xcnt.Company_Name__c);
for(Contact xcntc: existingCmp) {
if(xcnt.Company_Name__c == xcntc.Company_Name__c)
{
//Link contact to Account
}
else
{
//create new account
}
}
}
}
Is there any other approach I can follow?
I have requirement here:
When XYZ contact is created, check if a XYZ Company with exact Company Name field on Account exists.
If exists, link contact to the account. If Company does not exist, then create a new XYZ Account and set owner.
trigger TriggerContactInsert on Contact (before insert) {
List<String> cntCompName = new List<String>();
for(Contact xcnt: trigger.new)
{
cntCompName.add(xcnt.Company_Name__c);
}
list<Account> acctLst = [select Id, Name,(select Company_Name__c from Contacts) from Account where Name IN :cntCompName];
system.debug('Account' + acctLst);
Map<id,List<Contact>> mapofCmpNames = new Map<id,List<Contact>>();
for(Account l : acctlst)
{
for(List<Contact> e : l.Contacts)
{
mapofCmpNames.put(l.id, e);
}
}
for(Contact xcnt: trigger.new)
{
List<Contact> existingCmp = mapofCmpNames.get(xcnt.Company_Name__c);
for(Contact xcntc: existingCmp) {
if(xcnt.Company_Name__c == xcntc.Company_Name__c)
{
//Link contact to Account
}
else
{
//create new account
}
}
}
}
Is there any other approach I can follow?
Try this one
The above code fetches all acounts and in the iterates Trigger.New and checks if the Company Exists. If it exists attach it to the Account else creates a new Account.
Hope it Helps.
Regards.
All Answers
Try this one
The above code fetches all acounts and in the iterates Trigger.New and checks if the Company Exists. If it exists attach it to the Account else creates a new Account.
Hope it Helps.
Regards.