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
RAM RRAM R 

how to clone contact if i have update account field in contact

Can any one provide me code for clone the contact record if i have changed account value in the contact object .

and i want to see old record and cloned record here cloned record should be with new account Name.

i have tried this but not reached.
trigger cloneTrigger on Contact (after insert) {
    set<id> oid = new set<id>();
    for(Contact c : Trigger.new){
        if(c.Name == 'Test'){
            oid.add(c.Id);
            System.debug('cloningvalues:' + oid);
        }
    }
    list<Contact> olist = [select id,Name from Contact Where Id in:oid];
     map<id, contact> oldmap = new map<id, contact>([select id, name, contact.accountid from contact where id IN: oid]);  
      for(Contact ct :olist){
         Contact cont = new Contact();
          if(cont.Account != oldmap.get(cont.id).account)
          cont.Account = oldmap.get(cont.id).account;
        insert cont;
      }
 }

 
Best Answer chosen by RAM R
AshlekhAshlekh
Hi,

First thing when you are changing the Account on Conctact record it means contach is already created and you hve to write a trigger on Update event.

Here is the code : Suppose I have two account Acct A and Acct B. Acct A  have contact Con A and user has updated the Account Field on Con A from Acct A to Acct B then trigger will fire and create a clone of Con A with same Name Con A and  insert on Acct A. So now Acct A and Acct B both have contact.

 
trigger cloneTrigger on Contact (after Update) {
    
	set<id> oid = new set<id>();
	
	list<Contact> CloneContactForOldAccount = new List<contact>();
	
    for(Contact c : Trigger.new){
		Contact oldContact = Trigger.oldmap.get(c.id);
        if(oldContact.Accountid !=null && c.Accountid !=null ** oldContact.Accountid != c.Accountid){
            Contact co = c.clone(false);
			co.accountid= oldContact.AccountId;
			CloneContactForOldAccount.add(co);
	    }
    }
    
	if(CloneContactForOldAccount.size()>0)
		insert CloneContactForOldAccount;
	
 }

-Thanks
Ashlekh Gera