function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Pranav ChitransPranav Chitrans 

Trigger on lookup relationship

I am having 2 scenario something like this :
1. I have created one custom field named "lookup realtion" on standard object Account.. I want to fire trigger in such a way that when ever new account is inserted with the same name contact is being created and the custom field on Account which i have created should get populated with the contact name. and 
2. is on the account and contact I had created the custom field named "Checkbox" which is of checkbox type... and while insertion if account checkbox is checked the checkbox field on contact  should also be get checked and later on when i uncheck the checkbox on account the contact field checkbox also be get unchecked. I had written the code which perfectly well for creating the contact when ever new account is being created.. but I am facing problem in implementin these two above mentioned logics.. plz edit my code and suggest me your innovative Ideas..
public class CreateAccountContact 
{
 trigger CreateAccountContact on Account (after insert, after update){

if(Trigger.isInsert){

    List<Contact> ct = new List <Contact>();   
    for(Account acc : trigger.new){    
        Contact c = new Contact();       
                    c.LastName = acc.name;
                    c.AccountId=acc.id;
                    c.Fax=acc.Fax;
                    c.MailingStreet=acc.BillingStreet;
                    c.MailingCity=acc.BillingCity;
                    c.MailingState=acc.BillingState;              
                    c.MailingPostalCode=acc.BillingPostalCode;
                    c.MailingCountry=acc.BillingCountry;
                    c.Phone=acc.Phone;        
        ct.add(c);      
    }
   
    insert ct; 
}
}
}
Best Answer chosen by Pranav Chitrans
Pranav ChitransPranav Chitrans
public class testCreateAccountContact 
{
 
 public void OnAfterInsert(List<Account>triggerNew)
 {
  CreateContactOnAccont(triggerNew);
 }
 
 public void OnAfterUpdate(List<Account>triggerNew,map<Id,Account>triggerOldMap)
 {
  updateCheckbox(triggerNew,triggerOldMap);
 }
 

 public void CreateContactOnAccont(List<Account>triggerNew)
 {  
    List<Contact> ct = new List <Contact>();
    list<account>ListofUpdateAccount = new List<Account>();
    set<id>Accountid = new set<id>();
    for(Account acc :triggerNew){
        Accountid.add(acc.id);
        Contact c = new Contact();
                    c.LastName = acc.name;
                    c.AccountId=acc.id;
                    c.Fax=acc.Fax;
                    c.MailingStreet=acc.BillingStreet;
                    c.MailingCity=acc.BillingCity;                    
                    c.MailingState=acc.BillingState;
                    c.MailingPostalCode=acc.BillingPostalCode;
                    c.MailingCountry=acc.BillingCountry;
                    c.Phone=acc.Phone;
                    c.checkbox__c=acc.checkbox__c;
        ct.add(c);
    }
    insert ct; 
        Map<id,id> conMap = new Map<id,id>();;
        for(Contact con : [Select Name , AccountId from Contact where AccountId =: Accountid])
        {
          conMap.put(con.AccountId ,con.id);          
        }
        list<Account> acc =[select id ,Pranav__Contact_Custom_Lookup__c from Account where id=:Accountid];
        for(Account accessFiled :acc ){
          if(conMap.containskey(accessFiled.id)){
                  if(accessFiled.Pranav__Contact_Custom_Lookup__c == null){
                      Account newAcc= new Account();
                      newAcc.id = accessFiled.id;
                      newAcc.Pranav__Contact_Custom_Lookup__c = conMap.get(accessFiled.id);
                      ListofUpdateAccount.add(newAcc);
                  } 
          }
        }
     if(ListofUpdateAccount !=  null){
         update ListofUpdateAccount;
     }   
        
 }
 public void updateCheckbox(list<Account>triggerNew,map<Id,Account>triggerOldMap)
 {
   Map<Id,Account> accMap = new Map<Id,Account>([Select (Select checkbox__c from contacts) from Account where id IN : triggernew]);
   List<Contact> conListToUpdate = new List<Contact>();
   for(Account acc : triggerNew)
   {
    Account oldAcc = triggerOldMap.get(acc.id);    
    if(accMap.containsKey(acc.id) && oldAcc.checkbox__c != acc.checkbox__c)
    {
     for(Contact con : accMap.get(acc.id).contacts)
     {
     con.checkbox__c = acc.checkbox__c;
     conListToUpdate.add(con);
     }
    }
   }
   if(conListToUpdate.size() > 0)
   {
    update conListToUpdate;
   }
 }
}
Apex Trigger********
trigger CreateContact on Account (before insert, after insert, after update)
{
 testCreateAccountContact AccHelper =  new testCreateAccountContact();
 if(trigger.isafter && trigger.isInsert)
 {
  AccHelper.onBeforeInsert(trigger.New);
 }
 if(trigger.isAfter && trigger.isInsert)
 {
  AccHelper.OnAfterInsert(trigger.new);
 }
 if(trigger.isAfter && trigger.isUpdate)
 {
  AccHelper.OnAfterUpdate(trigger.new,trigger.oldMap);
 }
}
Final Solution is here  .... Finally... Working well

All Answers

Jithin Krishnan 2Jithin Krishnan 2
Hi Pranav,
Please try the below trigger and let me know if it works according to your need:
trigger UpdateContact on Account (before insert, before update) {
	List<Contact> contactList=new List<Contact>();
    if(trigger.isInsert){
        For(Account a: Trigger.new){
            Contact c=new Contact(lastName=a.name);
            c.Contact_checkbox__c=true;
            contactList.add(c);
            a.account_checkbox__c=true;
        }
        insert contactList;
    }
    if(trigger.isUpdate){
        For(Account a: Trigger.new){
            List<Contact> c= new List<Contact>([select id from contact where LastName=:a.name limit 1]);
            c[0].Contact_checkbox__c=a.account_checkbox__c;
            contactList.add(c[0]);
        }
        update contactList;
    }
}

Account_checkbox__c is the checkbox in account object and Contact_checkbox__c is the checkbox in contact object.
Thanks,
JK

 
Abhishek BansalAbhishek Bansal
Hi Pranav,

As per your requirement i have created a trigger for you.
Please find it below:
trigger handleContact on Account(after insert, after update){
	if(trigger.isInsert){
		List<Contact> conListToInsert = new List<Contact>();
		Contact newContact;
		for(Accout acc : trigger.new){
			newContact = new Contact();
			newContact.LastName = acc.name;
			newContact.AccountId = acc.id;
			newContact.Fax = acc.Fax;
			newContact.MailingStreet = acc.BillingStreet;
			newContact.MailingCity = acc.BillingCity;
			newContact.MailingState = acc.BillingState;              
			newContact.MailingPostalCode = acc.BillingPostalCode;
			newContact.MailingCountry = acc.BillingCountry;
			newContact.Phone = acc.Phone;
			
			//Please replace checkbox__c with the API name of your checkbox field created on Account and Contact
			newContact.checkbox__c = acc.checkbox__c;
			
			conListToInsert.add(newContact);
		}
		if(conListToInsert.size() > 0){
			insert conListToInsert;
		}
	}
	if(trigger.isUpdate){
		Map<Id,Account> accMap = new Map<Id,Account>([Select (Select checkbox__c from contacts) from Account where id IN : trigger.new]);
		List<Contact> conListToUpdate = new List<Contact>();
		
		for(Account acc : trigger.new){
			Account oldAcc = trigger.oldMap.get(acc.id);
			if(accMap.containsKey(acc.id) && oldAcc.checkbox__c != acc.checkbox__c){
				for(Contact con : accMap.get(acc.id).contacts){
					con.checkbox__c = acc.checkbox__c;
					conListToUpdate.add(con);
				}
			}
		}
		if(conListToUpdate.size() > 0){
			update conListToUpdate;
		}
	}
}

Please test your all cases and let me know if you have any issue in it.

Thanks,
Abhishek
Pranav ChitransPranav Chitrans

# Abhishek Bansal,
thanks.. It works well for checkbox... but what about my 1st issue... I have created one custom field named "lookup realtion" on standard object Account.. I want to fire trigger in such a way that when ever new account is inserted with the same name contact is being created and the custom field on Account which i have created should get populated with the contact name
Pranav ChitransPranav Chitrans
I had tried this by before insert and tried to populate the field by contact Id.. but the field remains the blank.. it does not getting any value...
Abhishek BansalAbhishek Bansal
Hi Pranav,

I have modified the trigger code according to both of your required cases.
Please change your trigger code with below code :
trigger handleContact on Account(before insert, after insert, after update){
	if(trigger.isBefore && trigger.isInsert){
		List<String> accNameList = new List<String>();
		for(Account acc : trigger.new){
			accNameList.add(acc.Name);
		}
		Map<String,Contact> conMap = new Map<String,Contact>();
		for(Contact con : [Select Name from Contact where Name IN :accNameList]){
			conMap.put(con.Name,con);
		}
		
		for(Account acc : trigger.new){
			if(conMap.containsKey(acc.Name)){
				//Please replace Relation__c with API name of your lookup relation field on Account
				acc.Relation__c = conMap.get(acc.Name).id;
			}
		}
	}

	if(trigger.isAfter && trigger.isInsert){
		List<Contact> conListToInsert = new List<Contact>();
		Contact newContact;
		for(Account acc : trigger.new){
			newContact = new Contact();
			newContact.LastName = acc.name;
			newContact.AccountId = acc.id;
			newContact.Fax = acc.Fax;
			newContact.MailingStreet = acc.BillingStreet;
			newContact.MailingCity = acc.BillingCity;
			newContact.MailingState = acc.BillingState;              
			newContact.MailingPostalCode = acc.BillingPostalCode;
			newContact.MailingCountry = acc.BillingCountry;
			newContact.Phone = acc.Phone;
			
			//Please replace checkbox__c with the API name of your checkbox field created on Account and Contact
			newContact.checkbox__c = acc.checkbox__c;
			
			conListToInsert.add(newContact);
		}
		if(conListToInsert.size() > 0){
			insert conListToInsert;
		}
	}
	if(trigger.isAfter && trigger.isUpdate){
		Map<Id,Account> accMap = new Map<Id,Account>([Select (Select checkbox__c from contacts) from Account where id IN : trigger.new]);
		List<Contact> conListToUpdate = new List<Contact>();
		
		for(Account acc : trigger.new){
			Account oldAcc = trigger.oldMap.get(acc.id);
			if(accMap.containsKey(acc.id) && oldAcc.checkbox__c != acc.checkbox__c){
				for(Contact con : accMap.get(acc.id).contacts){
					con.checkbox__c = acc.checkbox__c;
					conListToUpdate.add(con);
				}
			}
		}
		if(conListToUpdate.size() > 0){
			update conListToUpdate;
		}
	}
}
Check all of your cases now and let me know if you have any issue.

Thanks,
Abhishek
Pranav ChitransPranav Chitrans
its not working... The lookup field remain blank on account... why have you used trigger.isBefore... We want to perfom the event after the the account is being created.... on line 2
Pranav ChitransPranav Chitrans
I hade written this...
Apex trigger*******
trigger CreateContact on Account (before insert, after insert, after update)
{
 testCreateAccountContact AccHelper =  new testCreateAccountContact();
 if(trigger.isAfter && trigger.isInsert)
 {
  AccHelper.onBeforeInsert(trigger.New);
 }
 if(trigger.isAfter && trigger.isInsert)
 {
  AccHelper.OnAfterInsert(trigger.new);
 }
 if(trigger.isAfter && trigger.isUpdate)
 {
  AccHelper.OnAfterUpdate(trigger.new,trigger.oldMap);
 }
}

Apex Class***********
public class testCreateAccountContact 
{
 public void onBeforeInsert(List<Account>triggerNew)
 {
  CheckLookupRelation(triggerNew);
 }
 public void OnAfterInsert(List<Account>triggerNew)
 {
  CreateContactOnAccont(triggerNew);
 }
 
 public void OnAfterUpdate(List<Account>triggerNew,map<Id,Account>triggerOldMap)
 {
  updateCheckbox(triggerNew,triggerOldMap);
 }
 
 public void CheckLookupRelation(List<Account>triggerNew)
 {
  List<String> accNameList = new List<String>();
        for(Account acc : triggerNew)
        {
            accNameList.add(acc.Name);
        }
        Map<String,Contact> conMap = new Map<String,Contact>();
        for(Contact con : [Select Name from Contact where Name IN :accNameList])
        {
            conMap.put(con.Name,con);
        }
        
        for(Account acc : triggerNew){
            if(conMap.containsKey(acc.Name))
            {
                acc.Contact_Custom_Lookup__c= conMap.get(acc.Name).id;
            }
        }
    }

 public void CreateContactOnAccont(List<Account>triggerNew)
 {
    List<Contact> ct = new List <Contact>();
    
    for(Account acc :triggerNew){
        Contact c = new Contact();     
                    c.LastName = acc.name;
                    c.AccountId=acc.id;
                    c.Fax=acc.Fax;
                    c.MailingStreet=acc.BillingStreet;
                    c.MailingCity=acc.BillingCity;
                    c.MailingState=acc.BillingState;
                    c.MailingPostalCode=acc.BillingPostalCode;
                    c.MailingCountry=acc.BillingCountry;
                    c.Phone=acc.Phone;
                    c.checkbox__c=acc.checkbox__c;
     
        ct.add(c);
     
    }
   
    insert ct; 
 }
 public void updateCheckbox(list<Account>triggerNew,map<Id,Account>triggerOldMap)
 {
 
   Map<Id,Account> accMap = new Map<Id,Account>([Select (Select checkbox__c from contacts) from Account where id IN : triggernew]);

   List<Contact> conListToUpdate = new List<Contact>();
  
   for(Account acc : triggerNew)
   {
  
    Account oldAcc = triggerOldMap.get(acc.id);
  
    if(accMap.containsKey(acc.id) && oldAcc.checkbox__c != acc.checkbox__c)
    {
     for(Contact con : accMap.get(acc.id).contacts)
     {
     con.checkbox__c = acc.checkbox__c;
     conListToUpdate.add(con);
     }
    }
   }
   if(conListToUpdate.size() > 0)
   {
    update conListToUpdate;
   }
 }
}

it does not give any error..... but it not working for the lookup field..no value is being inserted....
Pranav ChitransPranav Chitrans
In apex trigger line 4..Instead of trigger.isAfter.. I had also checked with trigger.isBefore..but it doesn't work
Abhishek BansalAbhishek Bansal
Hi Pranav, Please comment all your classes and trigger code and just use the trigger cod provided by me. I dont know why do you want to change the value of Account in after insert event. Please check yopur cases with only the trigger code provided by me and than let me know if you have any issue. Thanks, Abhishek.
Pranav ChitransPranav Chitrans
i tried your code as you have written earlier... it have the same problem....
Abhishek BansalAbhishek Bansal
I dont understand why the code is not working for you. If it is possible for you than please share your org credentials or contact me on : Gmail : abhibansal2790@gmail.com OR Skpe : abhishek.bansal2790
Pranav ChitransPranav Chitrans
+Abhishek Bansal,
what i found is... I had seperately made the three methods... the last method updateCheckbox is correct because we have to perform the task after update also so we have to write diff method for this... but for creating contact and inserting value in lookup field we have to put both logics under one method.. becuase according to my code i had called first "CheckLookupRelation" which is for lookupfield and "CreateContactOnAccont" later on... and if this method is at second it will execute after the 1st method "CheckLookupRelation" executed... and to put value in account lookup we need Id... And we will not get any Id if it is before update.. I hope u are getting whta I am trying to say....
Pranav ChitransPranav Chitrans
and for further suggestion my skype id is( pranav.chitrans )
Noida uttarpradesh
Pranav ChitransPranav Chitrans
public class testCreateAccountContact 
{
 
 public void OnAfterInsert(List<Account>triggerNew)
 {
  CreateContactOnAccont(triggerNew);
 }
 
 public void OnAfterUpdate(List<Account>triggerNew,map<Id,Account>triggerOldMap)
 {
  updateCheckbox(triggerNew,triggerOldMap);
 }
 

 public void CreateContactOnAccont(List<Account>triggerNew)
 {  
    List<Contact> ct = new List <Contact>();
    list<account>ListofUpdateAccount = new List<Account>();
    set<id>Accountid = new set<id>();
    for(Account acc :triggerNew){
        Accountid.add(acc.id);
        Contact c = new Contact();
                    c.LastName = acc.name;
                    c.AccountId=acc.id;
                    c.Fax=acc.Fax;
                    c.MailingStreet=acc.BillingStreet;
                    c.MailingCity=acc.BillingCity;                    
                    c.MailingState=acc.BillingState;
                    c.MailingPostalCode=acc.BillingPostalCode;
                    c.MailingCountry=acc.BillingCountry;
                    c.Phone=acc.Phone;
                    c.checkbox__c=acc.checkbox__c;
        ct.add(c);
    }
    insert ct; 
        Map<id,id> conMap = new Map<id,id>();;
        for(Contact con : [Select Name , AccountId from Contact where AccountId =: Accountid])
        {
          conMap.put(con.AccountId ,con.id);          
        }
        list<Account> acc =[select id ,Pranav__Contact_Custom_Lookup__c from Account where id=:Accountid];
        for(Account accessFiled :acc ){
          if(conMap.containskey(accessFiled.id)){
                  if(accessFiled.Pranav__Contact_Custom_Lookup__c == null){
                      Account newAcc= new Account();
                      newAcc.id = accessFiled.id;
                      newAcc.Pranav__Contact_Custom_Lookup__c = conMap.get(accessFiled.id);
                      ListofUpdateAccount.add(newAcc);
                  } 
          }
        }
     if(ListofUpdateAccount !=  null){
         update ListofUpdateAccount;
     }   
        
 }
 public void updateCheckbox(list<Account>triggerNew,map<Id,Account>triggerOldMap)
 {
   Map<Id,Account> accMap = new Map<Id,Account>([Select (Select checkbox__c from contacts) from Account where id IN : triggernew]);
   List<Contact> conListToUpdate = new List<Contact>();
   for(Account acc : triggerNew)
   {
    Account oldAcc = triggerOldMap.get(acc.id);    
    if(accMap.containsKey(acc.id) && oldAcc.checkbox__c != acc.checkbox__c)
    {
     for(Contact con : accMap.get(acc.id).contacts)
     {
     con.checkbox__c = acc.checkbox__c;
     conListToUpdate.add(con);
     }
    }
   }
   if(conListToUpdate.size() > 0)
   {
    update conListToUpdate;
   }
 }
}
Apex Trigger********
trigger CreateContact on Account (before insert, after insert, after update)
{
 testCreateAccountContact AccHelper =  new testCreateAccountContact();
 if(trigger.isafter && trigger.isInsert)
 {
  AccHelper.onBeforeInsert(trigger.New);
 }
 if(trigger.isAfter && trigger.isInsert)
 {
  AccHelper.OnAfterInsert(trigger.new);
 }
 if(trigger.isAfter && trigger.isUpdate)
 {
  AccHelper.OnAfterUpdate(trigger.new,trigger.oldMap);
 }
}
Final Solution is here  .... Finally... Working well
This was selected as the best answer
Subodh shuklaSubodh shukla
Try this code
trigger CheckboxUpdate on Account ( before insert, before update, after insert ,after update) {
List<Contact> cnlist =new List<Contact>();

if(trigger.isbefore){
for(account ac: trigger.new){
ac.lookuprelation__c = ac.name;
}
}    
if(trigger.isInsert)
{
    for(account ac:trigger.new)
    {
       Contact c= new Contact();
       c.Accountid=ac.id;
       c.Lastname=ac.Name;
       c.Checkbox__c=ac.Checkbox__c;
      
       cnlist.add(c);
    }
    Insert cnlist;
}
if(trigger.isupdate)
{ 
    for(account ac:trigger.new){
   
        List<Contact> cn=[select id from contact Where  accountid IN :trigger.new ];
            for(integer i=0;i<cn.size();i++){ 
                cn[i].LastName=ac.Name;               
                cn[i].Checkbox__c=ac.Checkbox__c;
             }
             cnlist.addall(cn);
     } 
//Update a;
update cnlist;
}
}