+ Start a Discussion
Apps HeroApps Hero 

How to insert recod to a custom object from another custom object through a trigger

I am fairy new ,  I did something, Not any apex in the application, DId  objects, forumalas validations etc.  I am actually a relational database guy for 17 yeas. Worked with Oracle PL/SQL.


I read the apex work book, and tried to write the trigger, But did not work . Here is my scenario


I have 2 Objects  Change_Request__c   which is parent and  Change_History__c    which is child.

Whenever I change  the status value in the parent object and save, It must insert a new recod in the child object with parent id as foreign  key.

This should happend for each time the status changed.



Change_Request__c          -Parent


Request No






Status__c  ( Possible values "Approved", "Rejected", "Changed")






Change_History__c            -Child History_No

Request No ( Forign key from other other object)





Request_Date__c Status_changed_by_c ( user modify the record in the other Object

Status__c  ( Changed status in the other obeject)


Apps Hero,


Have you looked at the out-of-the-box functionality with Salesforce to capture history? If that works for you, there is no coding required.






Apps HeroApps Hero
No, The out of box will not work for me. My purpose is different and there will be other information in the child
I need to write trigger on the first object for after update event
Sean TanSean Tan

Something like this should do the trick:


trigger SyncStatusChange on Change_Request__c (after update)
	Change_History__c[] changeHistoryList = new Change_History__c[]{};
	for (Change_Request__c item : Trigger.new)
		if (item.Status__c != Trigger.oldMap.get(item.Id).Status__c)
			changeHistoryList.add(new Change_History__c
				Request_No__c = item.Id,
				Request_Name__c = item.Request_Name__c,
				Change_Type__c = item.Change_Type__c,
				Description__c = item.Description__c,
				Request_Date__c = item.Request_Date__c,
				Status_Changed_By__c = item.LastModifiedBy //Can also change this to UserInfo.getUserId() since triggers always fire in context of who performed the operation
				Status__c = item.Status__c
	if (!changeHistoryList.isEmpty())
		insert changeHistoryList;

Feel free to change the field values as you see fit.