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
UK 1UK 1 

trigger for creating child record based on parent record update

Hi Team,

I have 2 Objects, (Parent-abc__c & Child-CL__c) with loookup relationship.

There are 15 Picklist values in abc__c object.(eg: Country__c, State__c, Region__c, Gender__c.......)
There are 4 Fields in CL__c object(Old value, abc__c, NEW Value, action)

Now I want to create a child record(CL__c) if someone MODIFIES/UPDATES any of the 15 Picklist values.

The CL__c record must have the Old value as well as NEW value for user reference.

How to achieve this using trigger? any code samples? TIA

 
Best Answer chosen by UK 1
Niraj Kr SinghNiraj Kr Singh
Hi UK,

Try this code:
trigger CreateChildTrigger on abc__c (after insert, after update) {
	CreateChildHandler.createRecord(Trigger.old, Trigger.new);
}

public class CreateChildHandler {
	
	public static void createRecord(List<abc__c> lstOld, List<abc__c> lstNew) {
		List<CL__c> lstNewCL = new List<CL__c>();
		
		for(Integer index = 0; index < lstNew.size(); index++) {
			CL__c objCL = new CL__c();
			String oldPicklistValues = '';
			String newPicklistValues = '';
			
			if(Trigger.isUpdate && (
			  (lstOld[index].Country__c != lstNew[index].Country__c) 
			||(lstOld[index].State__c != lstNew[index].State__c)
			|| ...
			|| ...)) { //Add all 15 fields here with OR cndition like added for "Country" and "State"
				objCL.abc__c = lstNew[index].Id;
				
				if(lstOld[index].Country__c != lstNew[index].Country__c) {
					oldPicklistValues = oldPicklistValues + lstOld[index].Country__c + ',';
					newPicklistValues = newPicklistValues + lstNew[index].Country__c + ',';
				}
				if(lstOld[index].State__c != lstNew[index].State__c) {
					oldPicklistValues = oldPicklistValues + lstOld[index].State__c + ',';
					newPicklistValues = newPicklistValues + lstNew[index].State__c + ',';
				}
				.....
				..... //Add if condition for all remaining pikclist here
				.....
				
				//Finished if, then
				objCL.Old_value = oldPicklistValues;
				objCL.New_value = newPicklistValues;
				objCL.action = '';
				//Add Other required fields 
				
				lstNewCL.add(objCL);
				
			}
			else if(Trigger.isInsert) {
				objCL.abc__c = lstNew[index].Id;
				newPicklistValues = lstNew[index].Country__c + ',' + lstNew[index].State__c + ',' + <............. Add all remaining fields here>;
				objCL.Old_value = ''; //There is no old value.
				objCL.New_value = newPicklistValues;
				objCL.action = '';
				//Add Other required fields 
				
				lstNewCL.add(objCL);
			}
		}
		
		//Insert record
		if(!lstNewCL.isEmpty()) {
			insert lstNewCL;
		}
	}
	
}


Note: I have putted comments in code, update accordingly. Some update needed do from ur side.
If it helps you, Mark ur ans.

Thanks,
Niraj