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
MimiAMimiA 

Replicate Account Record

Hello,

I am new for apex classes. I was trying to create a trigger which replicate the account recorded to custom object. All account standard and custom field.

Could someone help me please?

Thanks
 
Best Answer chosen by MimiA
Marek Kosar_Marek Kosar_
Hello,
you mean copy all fields from Account to some custom object, with the same fields?
You can't clone it as it is different object, but you can do something like:
trigger createCopyOfAccountInCustomObject on Account(after insert, after update) {

  	if(Trigger.isInsert){
	  List<YourCustomObject__c> objToInsert = new List<YourCustomObject__c>();
	  for(Account acc : trigger.new){
	  	YourCustomObject__c obj = new YourCustomObject__c();
	  	obj.Name = acc.Name;
	  	obj.Phone = acc.Phone;
	  	obj.standardField = acc.standardField;
	  	obj.customfields__c = acc.customfields__c;
	  	etc....

	  	objToInsert.add(obj);
	  }
	  insert objToInsert;
	}
       
       if(Trigger.isUpdate){
       
           //query for cust.rec., and update them

       }
}

 

All Answers

Marek Kosar_Marek Kosar_
Hello,
you mean copy all fields from Account to some custom object, with the same fields?
You can't clone it as it is different object, but you can do something like:
trigger createCopyOfAccountInCustomObject on Account(after insert, after update) {

  	if(Trigger.isInsert){
	  List<YourCustomObject__c> objToInsert = new List<YourCustomObject__c>();
	  for(Account acc : trigger.new){
	  	YourCustomObject__c obj = new YourCustomObject__c();
	  	obj.Name = acc.Name;
	  	obj.Phone = acc.Phone;
	  	obj.standardField = acc.standardField;
	  	obj.customfields__c = acc.customfields__c;
	  	etc....

	  	objToInsert.add(obj);
	  }
	  insert objToInsert;
	}
       
       if(Trigger.isUpdate){
       
           //query for cust.rec., and update them

       }
}

 
This was selected as the best answer
povery.sf@gmail.compovery.sf@gmail.com
Account a = [SELECT id, Name FROM Account LIMIT 1];

// Use .clone to create a new copy:  clone(preserveId, isDeepClone, preserveReadonlyTimestamps, preserveAutonumber)
Account b = a.clone(false, true, false, false);
MimiAMimiA
Thanks a lot,

How would I do it generic? Whenever the custom field created that replicate to the custom Object?

Is there a way to do that?

Thanks
povery.sf@gmail.compovery.sf@gmail.com
You'd either need to hardcode it, as Marek suggested.   Or you could do it dynamically... something like this:
 
SObjectType accountType = Schema.getGlobalDescribe().get('Account');
Map<String,Schema.SObjectField> mfields = accountType.getDescribe().fields.getMap();

Account fromAccount = new Account(Name='MyAccount');
Account toAccount = new Account();

for (Schema.SObjectField field : mfields.values()) {
    try {
        toAccount.put(field, fromAccount.get(field));
    } catch (Exception ex) {
        // To catch attempts to write to read-only fields
    }
}
System.assertEquals(toAccount.Name, fromAccount.Name);

 
MimiAMimiA
Thanks a lot for your support. I got the idea.
MimiAMimiA
I have managed to create a dynamically mapping fields from my custom object to map and pass the field name. I have one problem. I map the address field to Account Billing field. I want to add Phone to be map as Phone__c from my custom object field. The code is as follows:


/*

Account_TriggerHandler

*/

public static void createNewCustomObjectReplicateFromAccount(List<Account> newA){
        
        List<Account> lstRequiredRecordTypefromAccount = new List<Account>();
        Id Required_REC_ID = Schema.SObjectType.Account.getRecordTypeInfosByName().get('TypeName').getRecordTypeId();
        
        List<String> fieldName = customObjService.getFieldName();
        Map<String,String> addressField = customObjService.getMapField();
        
        
        for(Account a : newA){
            if(a.RecordTypeId == Required_REC_ID) lstRequiredRecordTypefromAccount.add(a);
        }
        
        List<customObj__c> customObj2Insert = new List<customObj__c>();
        
        
        for(Account a : lstRequiredRecordTypefromAccount){
            
            customObj__c ss = new customObj__c(Account__c=a.Id);
            
            
            //Capture current date
            ss.custom_Date__c = Date.today();
            
            for(String f : fieldName){
                
                String ssField = (f.startsWith('Billing'))?addressField.get(f):f;
               
                
                //Only update the Account field when there is a value on customObj__c
                if(a.get(f) != null){
                    
                    ss.put(ssField,a.get(f));
    
                   
                    
                }
                
            }
            
            customObj2Insert.add(ss);
        }
        
        insert customObj2Insert;
        
        
    }
}

and from service:

public with sharing class customObjService {
    
    public static final Set<String> FIELD_NOT_MAPPED_TO_ACCOUNT = new Set<String>{'field1__c','field2__c','field3__c','Account__c','Id'};
    
    public static Map<String,String> addressField = getMapField();
    
            
    public static List<String> fieldName = getFieldName();
    

        
    public static List<String> getFieldName(){
        
        List<String> tmp = new List<String>();
        
        Map<String,String> mapField = getMapField();
        
        
        System.debug('>>>mapField: ' + mapField);
        
        Map<String, Schema.SObjectField> customObjMap = Schema.getGlobalDescribe().get('customObj__c'.toLowerCase()).getDescribe().Fields.getMap();
        //Get all field name from customObj__c sObject
        if (customObjMap != null){
            for (Schema.SObjectField ft : customObjMap.values()){
                String f = ft.getDescribe().getName();
                Integer len = f.length() - 3;
                
                if(f.indexOf('__c') == len && !customObjService.FIELD_NOT_MAPPED_TO_ACCOUNT.contains(f)){
                    tmp.add((f.startsWith('Address'))?mapField.get(f):f);
                    
                    system.debug('tmp >>>' + tmp);
                }
                
            }
        }
        //system.debug('tmp >>>' + tmp);
        return tmp;
    }
    
   
    
    public static Map<String,String> getMapField(){
        
        Map<String,String> tmp = new Map<String,String>();
        //From Custom Object to Account
        tmp.put('Address_Street__c','BillingStreet');
        tmp.put('Address_City__c','BillingCity');
        tmp.put('Address_Country__c','BillingCountry');
        tmp.put('Address_State_Province__c','BillingState');
        tmp.put('Address_Zip_Postal_Code__c','BillingPostalCode');
        
        
        
        //From Account to Custom Object
        tmp.put('BillingStreet','Address_Street__c');
        tmp.put('BillingCity','Address_City__c');
        tmp.put('BillingCountry','Address_Country__c');
        tmp.put('BillingState','Address_State_Province__c');
        tmp.put('BillingPostalCode','Address_Zip_Postal_Code__c');
        
        
        return tmp;
    }
}

Please let me know how to include  standard  fields like Phone.

Thanks for your help
MimiAMimiA
Any ideas please?
MimiAMimiA
Thanks I fix the problem.