3.4 Write a more difficult trigger

The scenario

In this scenario, we will capture how many overall revenue does a single merchandise capture. Suppose we are selling bicycles. The price of one bicycle is 100. And we have sold three bicycles in total. Then the total revenue should be 300.

Now, let’s assume the transaction records don’t update. We just insert into the database and that’s it.

In order to handle this scenario, we need to build two more fields first. Amount in transaction object and Overall revenue in merchandise object. Both fields should be numbers.

What the trigger does is: each time a new transaction is made, it adds into the overall revenue of corresponding merchandise.

The code


trigger TransactionTrigger on Transaction__c (after insert) 
{
    List<String> relatedMerchandiseIdList = new List<String>();
    for(Transaction__c curTrans: Trigger.New)
    {
        relatedMerchandiseIdList.add(curTrans.Merchandise__c);
    }
    
    Map<Id, Merchandise__c> merMap = new Map<Id, Merchandise__c>([Select Id, Name, 
                                                                 		Overall_Revenue__c,
                                                                 		Discounted_Price__c 
                                                                  From  Merchandise__c
                                                                  Where Id in :relatedMerchandiseIdList]);
    for(Transaction__c curTrans: Trigger.New)
    {
        Merchandise__c mer = merMap.get(curTrans.Merchandise__c);
        if(mer.Overall_Revenue__c == null) 
        {
            mer.Overall_Revenue__c = mer.Discounted_Price__c * curTrans.Amount__c;
        } 
        else 
        {
            mer.Overall_Revenue__c += mer.Discounted_Price__c * curTrans.Amount__c;
        }
    }
    update merMap.values();
}

This trigger is much more complicated than the previous one. Although all the grammars are already explained before. The thinkings about how to write such a trigger is still not an easy job for beginners. I will explain in details in the next post. For now, just read through the code and understand how it is functioning.

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *