4.1 Write an advanced trigger

The scenario

Our customers can put a balance in our accounts now. They can have a balance in our system. So, now, for every purchase they made, we will need to subtract that amount  from their current balance.

The code

Although this can be considered as an advanced trigger, if you understand out last example thoroughly, you can probably write this trigger by yourself now. Or at least, you might have some idea about it already. If so, try to write it yourself before reading my code below.


trigger CustomerBalance on Transaction__c (after insert) 
{
	List<String> relatedMerchandiseIdList = new List<String>();
    List<String> relatedCustomerIdList = new List<String>();
	for(Transaction__c curTrans: Trigger.New)
    {
        relatedMerchandiseIdList.add(curTrans.Merchandise__c);
        relatedCustomerIdList.add(curTrans.Customer__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]);
    Map<Id, Customer__c> custMap = new Map<Id, Customer__c>([Select Id, Name,
                                                            		Balance__c
                                                             From   Customer__c
                                                             Where  Id in :relatedCustomerIdList]);
    for(Transaction__c curTrans: Trigger.New)
    {
        Merchandise__c mer = merMap.get(curTrans.Merchandise__c);
        Customer__c cust = custMap.get(curTrans.Customer__c);
        if(cust.Balance__c  == null) 
        {
            cust.Balance__c = 0 - mer.Discounted_Price__c * curTrans.Amount__c;
        } 
        else 
        {
            cust.Balance__c -= mer.Discounted_Price__c * curTrans.Amount__c;
        }
    }
    update custMap.values();
}

A little bit explanation

This trigger actually is not much more complicated than the previous one. It’s just one more related object involved. Also, the trigger has to be on transaction object. Read it more and understand the structure of it. If you can write such a trigger on your own. You shouldn’t have much problem implementing triggers in the future.

Next Post

4.2 Introducing trigger handler class

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 *