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
FlashheartFlashheart 

Triggers within Triggers?

Hi all, 

 

am new to Sfdc / apex - so forgive the naivety - I've scoured the boards and other material but cant see how/whether the following can be done.

 

Can a trigger be added to an object (Bookings) to create a record in another object (Expense) as a "after insert" trigger
where there is also a "before insert" trigger active ?

 

I have 3 custom objects:

 

Bookings - the capture of a hotel reservation details with a related contact record, payments etc. etc.
Expense - to capture the associated costs of all bookings
Materials - a reference table of materials used for the hotel

 

The first trigger is an "after insert" trigger on Bookings that needs to create a corresponding record in Expense object

 

The second trigger is a "before insert" trigger that does 2 things:

1. takes output of a numeric formula field: Expense.total_nights__c (for example here lets call this "p")

2. Applies (p) * each record type in Materials where Materials.Service__c = Booking

 

Firstly is this possible?, secondly, forgive my naivety but is there any reference code available that does this (or something similar)  or would anyone be brave enought to suggest what this needs to look like?

 

I've had a go and am continually trying but stumblingn in the dark so thought it a good idea to post for help here

 

thanks!

Janet GuoJanet Guo

Hi Flashheart,

 

Welcome to Apex!

 

And yes, you can insert or update other records while within a trigger for one specific object. You can use DML calls like insert, update, delete, etc. at any time within one trigger to fire off a trigger for another object.

 

For example, in the first trigger you mentioned, if might look something like this pseudo-code:

if(Trigger.isAfter){
	// have a list ready for inserting the new Expense records
	Expense__c lstExpense = new Expense[]{};
	
	// iterate through all the Bookings in Trigger.new to create relevant 
	// Expense records and add those records to lstExpense
	for(Booking__c booking: Trigger.new){
		// grab whatever relevant information from the booking record
		// and create an Expense record with the information
		// and add new Expense record to list of Expense records
		lstExpense.add(expenseRec);
	}
	
	// and here, you can insert those new Expense records which will
	// also fire off whatever Expense object triggers there are
	insert lstExpense;
}

 

You can do something similar for something that occurs in the before trigger (just replace the Trigger.isAfter with Trigger.isBefore).

 

I hope that helps. In place of "insert" you can also use other DML operations.

 

If you post with something a bit more specifi, I might be able to give more tailored advice.

 

Good luck!