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
Suman MSuman M 

Help on Record creation in new Object based on update/create in other Object

Hi All,

 

Could someone please help me on the below requirement.

 

I'm creating a New Object named ' History_Object ', Whenever I create or update a record in another Object, There should be a Record Created in the History_Object. How to achieve this.

 

Someone please help me ASAP. Thank You. 

prakash_sfdcprakash_sfdc

You can create an "after insert,after update" trigger on another object. Assume your custom object name is TestObject, the trigger would be like

trigger on TestObject(after insert,after update){
for(TestObject t:Trigger.new)
{
History_Object temp=new History_Object();
temp.Field1='aaa';
temp.Field2='aaa';
insert temp;
}
}

Rahul SharmaRahul Sharma

Trigger is perfect solution for this scenario as suggested by Prakash, but make sure you follow salesforce best practices.

Suman MSuman M

Hi Prakash, Thank You for the help.  I'm getting an error when I tried this. Could you please help me

 

Objects: Histroy_Object__c and Candidate__c

 

As per the requirement. I Have created a Lookup from History_Object to Candidate Object. and as you said I have written a Trigger on Candidate Object. as below.

 

trigger RectoHistoryObj on Candidate__c (after insert, after update)
{
 for(Candidate__c can:Trigger.new)
 {
  History_Object__c temp = new History_Object__c();
  temp.Candidate_Name__c = Can.First_Name__c;
  insert temp;
 }
}

 

Trigger is getting saved, But when I tried to edit or create a new Candidate Object I'm getting the below error.

 

' Apex trigger RectoHistoryObj caused an unexpected exception, contact your administrator: RectoHistoryObj: execution of AfterInsert caused by: System.StringException: Invalid id: Nick: Trigger.RectoHistoryObj: line 6, column 1 '

 

Please helpme on the above. Thank You.

 

 

Suman MSuman M
Without creating a Lookup between the two Objects. It is working Fine. But what are things need to be taken care when a Lookup is created between the Objectsa and i have to update the Lookup Field. Thank You.
prakash_sfdcprakash_sfdc

Hi,

You have to assign ID to Lookup fields. Just change the code as follows:
trigger RectoHistoryObj on Candidate__c (after insert, after update)
{
for(Candidate__c can:Trigger.new)
{
History_Object__c temp = new History_Object__c();
temp.Candidate_Name__c = can.ID;
insert temp;
}
}

 

Please mark it as solution and give kudos if it helped.