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
Denise FloodDenise Flood 

Create a trigger

Hi 

I am trying to set up a trigger for the following:

Create a new record in a custom object called Audit when a previous record is marked closed.
The Name of the new record would be called Account Name(linked to the account on the previous record) - Audit - Date Created.


How would it be recommended that I complete this task?

Thank you
Best Answer chosen by Denise Flood
Vinit_KumarVinit_Kumar
Try below code :-

trigger createNewRecord on Audit__c (before update){
   list<Audit__c> newList = new list<Audit__c>();
   
   for (Audit__c p:Trigger.new){
	
     if ((p.Status__c!=trigger.oldMap.get(p.id).Status__c)&&(p.Status__c=='Closed')){ //Assuming that the field to check Closed is Status__c
		
		Audit__c au = new Audit__c(Account__c=p.Account__c,Status__c=<new status>);//Populate all the fields req//uired to insert a new Audit__c record
		newList.add(au);
     }
   }
   if(newList.size()>0)
   {
      insert newList;
   }	  
}

If this helps,please mark it as best answer to help others :)

All Answers

kevin Carotherskevin Carothers
So, when an autit record is closed, you want another audit record created linked to the same account?


Denise FloodDenise Flood
Yes correct
Vinit_KumarVinit_Kumar
Try below code :-

trigger createNewRecord on Audit__c (before update){
   list<Audit__c> newList = new list<Audit__c>();
   
   for (Audit__c p:Trigger.new){
	
     if ((p.Status__c!=trigger.oldMap.get(p.id).Status__c)&&(p.Status__c=='Closed')){ //Assuming that the field to check Closed is Status__c
		
		Audit__c au = new Audit__c(Account__c=p.Account__c,Status__c=<new status>);//Populate all the fields req//uired to insert a new Audit__c record
		newList.add(au);
     }
   }
   if(newList.size()>0)
   {
      insert newList;
   }	  
}

If this helps,please mark it as best answer to help others :)
This was selected as the best answer
Denise FloodDenise Flood
Hi Thank you for your reply, this is exactly what I am looking for except it is creating 2 new records and the Audit name is referencing an ID number instead of Account Name(linked to the account on the previous record) - Audit - Date Created. If you can help me with this I would appreciate it. Thanks