Triggers in Salesforce

Triggers in Salesforce - All You Need to Know


A trigger is a piece of code that runs before and after a record in the database is inserted, updated, or deleted. Triggers can be used to bring Apex to life. A trigger is a functional action that occurs in response to specific events. Triggers will occur both before and after records are entered and exited the database. Each occurrence serves as a trigger.


 Update All Child Email When Parent Object field Email is updated

dont miss out iconDon't forget to check out: Trigger Assignment Rules on Update or Upsert using Data Loader | Salesforce Tutorials

Apex Class Code

public class StudentClass {
    public static void updateEmailMethod(list<student__c> stulist){
        list<Fee__c> feelist = [select id, email__c, student__r.email__c from Fee__c where in: stulist];
        system.debug('feelist' +feelist);
        list<fee__c> feeupdate = new list<fee__c>();
        for(fee__c f : feelist){
                f.Email__c = f.student__r.email__c;
        update feeupdate;

Trigger Code

trigger mailUpdateOfFee on Student__c (after update) {
    if(Trigger.isafter && Trigger.isupdate){

Example 2:-

When Value of Course fee(Custom field ) in Fee Custom Object is summed as.

In Total fee(Custom field) in Student Custom Object.

dont miss out iconCheck out another amazing blog by Arpit here: Opportunity Line Item | Salesforce Developer Guide

Trigger Code

trigger totalAmount on Fee__c (after insert, after update, after delete) {
    Set<id> studentIds = new Set<id>();
    List<Student__c> StudentsToUpdate = new List<Student__c>();
    //if(Trigger.isinsert && Trigger.isafter){
        for (Fee__c c : {
        if (Trigger.isUpdate || Trigger.isDelete) {       
            for (Fee__c c : Trigger.old) {
        Map<id, Student__c> studentMap = new Map<id, Student__c>([select id, Total_Fees__c  from Student__c where id IN :studentIds]);   
        List<AggregateResult> ars = [SELECT Student__c , sum(Course_Fees__c) FROM Fee__c WHERE Student__c  IN :studentIds group by Student__c ];    
        for (AggregateResult ar : ars) {
            studentMap.get(String.valueOf(ar.get('Student__c'))).Total_Fees__c = Integer.valueOf(ar.get('expr0'));
            //StudentsToUpdate.add(studentMap.get(String.valueOf(ar.get('Student__c '))));
        update StudentsToUpdate;


Popular Salesforce Blogs