Advertisement
f1lam3ntx0

create contact with lookup to account when account is craeted

Aug 21st, 2022
1,330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. 5. Create a field on Account Named (Client Contact lookup to Contact). Once an Account is inserted a Contact will create with the name of the Account and that Contact will be the Client Contact on the Account.
  2.  
  3. ===========\\\\\\\\\===============
  4.  
  5. > when we want to create a field with lookup relation we want to create some empty list and Map
  6. > list for contact to be updated
  7. > list for account to be updated
  8. > set for account to get the Id's from trigger.new
  9. > map for checking the lookup relation between contact and account.
  10.  
  11. ++++++++++++\\\\\\\\\+++++++++++++++
  12.  
  13.  
  14. Trigger contactOnAccountTrigger on Account (After Insert){
  15.  switch on Trigger.OperationType{
  16.   when AFTER_INSERT{
  17.    contactOnAccountHelper.createContactOnAccount(Trigger.new);
  18.   }
  19.  }
  20. }
  21.  
  22. Public with sharing class contactOnAccountHelper{
  23. public static void createContactOnAccount(List<Account> accList){
  24.  if(accList != null){
  25.   Set<Account> accSet = new Set<Account>();
  26.   for(Account acc : accList){
  27.      accSet.add(acc.Id);
  28.   }
  29.      List<Contact> conInserted = new contact();
  30.   for( Account accContact : accList){
  31.   contact con = new contact();
  32.   con.LastName = accContact.name;
  33.   con.accountId = accContact.Id;
  34.   conInserted.add(con);
  35.   accSet.add(con.AccountId);
  36.   }
  37.   if(conInserted.size() > 0 && conInserted != null ){
  38.   INSERT conInserted;
  39.   }
  40.  }
  41.  List<Account> accLkp = [SELECT id, name , Client_Contact__C from account where Id=: accSset];
  42.  Map<Id, Account> accMap = new Map<Id, Account>();
  43.  List<Account> accUpdated = new List<Account>();
  44.  if(accLkp.size() > 0){
  45.  for(Account acc: accLkp){
  46.  accMap.put(acc.Id, acc);
  47.  }
  48.  }
  49.  if(conInserted.size() > 0){
  50.  for(Contact con: conInserted){
  51.  if(accMap.containsKey(con.AccountId)){
  52.  Account aObj = accMap.get(con.AccountId);
  53.  accUpdated.add(aObj);
  54.  }
  55.  }
  56.  }
  57.  // check for the new account list to update.
  58.  if(accUpdated.size() > 0 ){
  59.  UPDATE accUpdated;
  60.  }
  61. }
  62. }
  63.  
Tags: Triggers
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement