Create Super Clone Button To clone 3 level of Hierarchy :
Object Schema
Create JavaScript Button on Account Detail page :{!REQUIRESCRIPT("/soap/ajax/19.0/connection.js")} {!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")} try{ alert("Entered try"); var accId='{!Account.Id}'; alert('____1___'+accId); sforce.apex.execute("superClone","createClone",{accId:accId}); alert('____2___'+accId); txt="Clones Create"; alert(txt); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Error description: " + err.description + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); } |
Apex class Code :Class Name superClone
global class superClone {
static Map<Id,Id> newoldcon=new Map<Id,Id>();
webservice static void createClone(String accId)
{
system.debug(accId);
Account acc= [SELECT ID, Name FROM Account WHERE Id = :accId];
system.debug(acc);
Account acccopy=acc.clone(false,true);
acccopy.Name=acc.Name+'Clonedcopy';
insert acccopy; // Grand Parent
List<Contact> con = [SELECT Id, LastName, AccountId FROM Contact WHERE AccountId = : acc.Id];
List<Contact> consdup= new List<Contact>();
List<Id> cid = new List<Id>();
if(con!=null)
{
for(Contact c:con)
{
cid.add(c.Id);
Contact concopy=c.clone(false,true);
concopy.AccountId=acccopy.Id;
concopy.LastName =c.LastName + 'clonecopy';
consdup.add(concopy);
}
}
Database.insert(consdup); // Parent
if(consdup!=null && cid!=null)
{
for(ID i:cid)
{
for(Contact c1:consdup)
{
newoldcon.put(i,c1.id);
}
//createDivCon(i);
}
}
System.debug('newoldcon++++++ old id '+newoldcon.keySet());
List<Divsional_Contact__c> divlist=[SELECT Id,Name,Contact_Parent__c FROM Divsional_Contact__c WHERE Contact_Parent__c=:newoldcon.keySet()];
System.debug('divisional list-------------******'+divlist);
List<Divsional_Contact__c> divlist1=new List<Divsional_Contact__c>();
if(divlist!=null)
{
for(Divsional_Contact__c d: divlist)
{
Divsional_Contact__c divcopy=d.clone(false,true);
divcopy.Contact_Parent__c=newoldcon.get(d.Contact_Parent__c);
divcopy.Name=d.Name+'Cloned Copy';
divlist1.add(divcopy);
}
} System.debug('--------------- ++++++divlist1 list'+divlist1);
Database.insert(divlist1);
}
}
Credits goes to @Preeti