Hey guys, today in this post we are going to learn about Write a Apex Trigger on Contact to Create Account Automatically and map to related account Id to Contact Whenever Contact is Created in Salesforce.
Real time scenarios:- Write a Trigger on Contact to Create Account Automatically Along with Name and Phone Number and map to related Account Id to Contact Whenever New Contact is Created.
Files we used in this post example
CreateAutoAccountFromContact.apxt | Apex Class Trigger | It will be fired whenever New Contact is Created |
Parent Cusotm Object:- Account | Parent Object (Account) | Trigger on Child Object (Contact) and Account is Auto created whenever new contact is created |
Child Object:- Contact | Child Object (Contact) | It is child object and associated with Account Object Automatically when new contact is created |
Live Demo
Other related post that would you like to learn.
Step 1:- Create Apex Class : CreateAutoAccountFromContact.apxt
From Developer Console >> File >> New >> Apex Class
CreateAutoAccountFromContact.apxt [Apex Class Trigger]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
trigger CreateAutoAccountFromContact on Contact (before insert, after insert){ if(trigger.isBefore){ system.debug('trigger before event'); if(trigger.isInsert){ List<Contact> listOfContact = new List<Contact>(); for (Contact conObj : trigger.new) { if (String.isBlank(conObj.accountid)) { listOfContact.add(conObj); } } system.debug('listOfContact_1 ' + listOfContact); if (listOfContact.size() > 0) { List<Account> createNewAcc = new List<Account>(); Map<String,Contact> conNameKeys = new Map<String,Contact>(); for (Contact con : listOfContact) { String accountName = con.firstname + ' ' + con.lastname; conNameKeys.put(accountName,con); Account accObj = new Account(); accObj.Name = accountName; accObj.Phone= con.MobilePhone; createNewAcc.add(accObj); } Insert createNewAcc; for (Account acc : createNewAcc) { system.debug('mapContainsKey ' + conNameKeys.containsKey(acc.Name)); if (conNameKeys.containsKey(acc.Name)) { conNameKeys.get(acc.Name).accountId = acc.Id; } } } } } else if(trigger.isAfter){ system.debug('trigger after event'); } } |
Other post that would you like to learn in LWC
Further post that would you like to learn in LWC
Article is best