Develop a trigger that automatically associates new Contact records with an Account based on a custom field on the Contact record called ExternalAccountID matching the AccountNumber of an Account.
Hi @Swati Patle
For this requirement you can write trigger like this.
trigger ContactWithAccount on Contact (before insert, before update) {
if (Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)) {
Set<Id> accIds = new Set<Id>();
for (Contact con: Trigger.new) {
accIds.add(con.AccountId);
}
Map<Id, Account> accMap = new Map<Id, Account>([SELECT Id, AccountNumber FROM Account WHERE Id IN :accIds]);
for (Contact con: Trigger.new) {
Account acc = accMap?.get(con.AccountId);
if (con.ExternalAccountID__c == acc.AccountNumber) {
con.AccountId = acc.Id;
} else {
con.adderror('To associate Contact with Account ExternalAccountID and Account\'s AccountNumber should be same');
}
}
}
}
Hope this will solve your problem.