Skip to main content

Top 5 trigger scenarios in salesforce

 

1)  Write a trigger on the Account when the Account is updated check all opportunities related to the account. Update all Opportunities Stage to close lost if an opportunity created date is greater than 30 days from today and stage not equal to close won.



trigger UpdateOpportunitiesOnAccountUpdate on Account (after update) {

    

    // Get the IDs of all the updated Accounts

    Set<Id> accountIds = new Set<Id>();

    for (Account acc : Trigger.new) {

        accountIds.add(acc.Id);

    }

    

    // Query for all Opportunities related to the updated Accounts

    List<Opportunity> opportunitiesToUpdate = [

        SELECT Id, StageName, CreatedDate

        FROM Opportunity

        WHERE AccountId IN :accountIds

    ];

    

    // Update Opportunities that meet the criteria

    List<Opportunity> opportunitiesToUpdateStage = new List<Opportunity>();

    for (Opportunity opp : opportunitiesToUpdate) {

        if (opp.CreatedDate.addDays(30) < Date.today() && opp.StageName != 'Closed Won') {

            opp.StageName = 'Closed Lost';

            opportunitiesToUpdateStage.add(opp);

        }

    }

    

    // Save the updated Opportunities

    if (!opportunitiesToUpdateStage.isEmpty()) {

        update opportunitiesToUpdateStage;

    }

    

}



2) Once an Account is inserted an email should go to the System Admin user with specified text below.

An account has been created and the name is “Account Name”.


trigger SendEmailOnAccountInsert on Account (after insert) {

    

    // Get the email address of the System Admin user

    User adminUser = [

        SELECT Email

        FROM User

        WHERE Profile.Name = 'System Administrator'

        LIMIT 1

    ];

    

    // Create the email message

    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

    email.setToAddresses(new List<String>{ adminUser.Email });

    email.setSubject('New Account Created');

    email.setPlainTextBody('An account has been created and the name is "' + Trigger.new[0].Name + '".');

    

    // Send the email

    Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{ email });

    

}



3) Once an Account will update then that Account will update with the total amount from All its Opportunities on the Account Level. The account field name would be ” Total Opportunity Amount “.


trigger UpdateAccountTotalAmount on Opportunity (after insert, after update, after delete) {

    

    // Get the IDs of all Accounts related to the Opportunities being updated or deleted

    Set<Id> accountIds = new Set<Id>();

    for (Opportunity opp : Trigger.new) {

        accountIds.add(opp.AccountId);

    }

    for (Opportunity opp : Trigger.old) {

        accountIds.add(opp.AccountId);

    }

    

    // Query for all Accounts related to the updated or deleted Opportunities

    List<Account> accountsToUpdate = [

        SELECT Id, Name, (SELECT Id, Amount FROM Opportunities)

        FROM Account

        WHERE Id IN :accountIds

    ];

    

    // Loop through each Account and update the Total Opportunity Amount field

    for (Account acc : accountsToUpdate) {

        Decimal totalAmount = 0;

        for (Opportunity opp : acc.Opportunities) {

            if (opp.StageName != 'Closed Won') {

                continue; // exclude opportunities that aren't Closed Won

            }

            totalAmount += opp.Amount;

        }

        acc.Total_Opportunity_Amount__c = totalAmount;

    }

    

    // Save the updated Accounts

    if (!accountsToUpdate.isEmpty()) {

        update accountsToUpdate;

    }

    

}



4) Write a trigger on contact to prevent duplicate records based on Contact Email & Contact Phone.



trigger PreventDuplicateContacts on Contact (before insert, before update) {

    

    // Create sets to hold unique email and phone values

    Set<String> uniqueEmails = new Set<String>();

    Set<String> uniquePhones = new Set<String>();

    

    // Loop through each Contact in the trigger context

    for (Contact cont : Trigger.new) {

        

        // Check if the Contact's Email is a duplicate

        if (cont.Email != null && uniqueEmails.contains(cont.Email)) {

            cont.Email.addError('A Contact with this Email already exists.');

        } else {

            uniqueEmails.add(cont.Email);

        }

        

        // Check if the Contact's Phone is a duplicate

        if (cont.Phone != null && uniquePhones.contains(cont.Phone)) {

            cont.Phone.addError('A Contact with this Phone already exists.');

        } else {

            uniquePhones.add(cont.Phone);

        }

        

    }

    

}



5) Write a trigger, only the system admin user should be able to delete the task.



trigger PreventTaskDeletion on Task (before delete) {

    

    // Get the ID of the System Admin profile

    Id systemAdminProfileId = [

        SELECT Id

        FROM Profile

        WHERE Name = 'System Administrator'

        LIMIT 1

    ].Id;

    

    // Get the ID of the current user

    Id currentUserId = UserInfo.getUserId();

    

    // Check if the current user is a System Admin

    Boolean isSystemAdmin = [

        SELECT COUNT()

        FROM User

        WHERE Id = :currentUserId

        AND ProfileId = :systemAdminProfileId

    ] > 0;

    

    // If the current user is not a System Admin, prevent the Task from being deleted

    if (!isSystemAdmin) {

        for (Task t : Trigger.old) {

            t.addError('Only the System Administrator can delete Task records.');

        }

    }

    

}




Comments

Popular Posts

Top 100 Most common used Apex Method in Salesforce

  Here are 100 more Apex methods in Salesforce: 1.       insert: Inserts records into the database. 2.       update: Updates records in the database. 3.       delete: Deletes records from the database. 4.       upsert: Updates or inserts records into the database. 5.       query: Retrieves records from the database using SOQL. 6.       getContent: Retrieves the content of a document or attachment. 7.       getContentAsPDF: Generates a PDF file from a Visualforce page or HTML content. 8.       addError: Adds a custom error message to a record and prevents saving. 9.       start: Initiates processing in batch Apex. 10.    execute: Processes a batch of records in batch Apex. 11.    finish: Finalizes processing in batch Apex....

How to create ICS/Calendar File | Helps you to download the calendar invites

  Want to know how to create ICS(Internet Calendar Scheduling) file for Business purpose....👀    ICS (Internet Calendar Scheduling) file is a calendar file saved in a universal calendar format used by several email and calendar programs, including Microsoft Outlook, Google Calendar, Notes and Apple Calendar. It enables users to publish and share calendar information on the web and over email. Lets see the code. The code is written in lwc(Lightning web component). HTML:   <template> <div class="login-container"> <h1 style="size: 14px;"><b>Create ICS File</b></h1> <div class="form-group"> <lightning-input type="datetime" name="input1" value={EventEndValue} onchange={startDate} label="Enter Start date/time value" ></lightning-input> </div> <div class="form-group"> <lightning-input type="...

Sharing records by Apex in Salesforce

  Greetings, everyone! In today's session, we'll delve into the topic of sharing records within an Apex class. As we're aware, there exist various methods through which we can accomplish the sharing of records. We engage in record sharing primarily when the object's Organization Wide Default (OWD) settings are set to private. Sharing settings come into play when certain predefined criteria are met, allowing us to extend access to records to designated groups or roles. In cases where intricate logic is involved, manual sharing is employed. While this approach proves beneficial for specific records, instances where a multitude of records require automated handling, Apex sharing becomes the preferred solution. Salesforce offers a 'Share' object for each type of object, with distinct naming conventions: For standard objects, it's 'StandardobjectName+Share', such as 'AccountShare' for the 'Account' object. Custom objects follow the pattern...

Login Salesforce Without Credentials(Without UserName and Password)

  Want to login into Salesforce without credentials. Please follow the below STEPS: STEPS:-  1)  Goto to setup  --> Open Developer Console. 2) Goto debug --> Open Execute Anonymous Window --> It will open the pop. 3) Please write the below code in Anonymous window.       String sessionId = UserInfo.getOrganizationId() + '' + UserInfo.getSessionId().SubString(15);      System.debug('$$$$ Session Id ' + sessionId); 4) Click on Execute and filter the debug. You can see one session Id with Organization Id. Now, we have to copy the debug session Id and create one login URL. Steps to create Login URL: 1) Copy the Salesforce URL. Please refer the screenshot shown below. 2) Now concatenate the session Id with the salesforce URL and your Session Id Will look like below. https://d5g000004zfq2eai-dev-ed.lightning.force.com/secur/frontdoor.jsp?sid=00D5g000004zfQ2EAI!AQgAQKzTcnQTifXpRnQ7DgECtk_rv.w9BT5FoPEAmoy_UrgG4HJ6B9YFpQ2LVlmnJhBrYPSf8cI...

SF Fact #03 | Undelete Failed, Entity is not in recycle bin

  Similar to ENTITY_IS_DELETED error, if we attempt to undelete a record from recycle bin by mistake which has already been hard deleted, the following error is encountered: UNDELETE_FAILED. When a record is deleted, it moves to the Recycle Bin. This is known as "soft deletion," allowing the record to be easily restored through the user interface. However, under certain conditions, a deleted record will no longer appear in the Recycle Bin: Master-Detail Relationship (Child Deleted First): If a record is a child or detail in a master-detail relationship and it is deleted before its parent record, then after the parent is deleted, the child record transitions to a "hard deleted" status. In this state, the child record cannot be recovered through the Recycle Bin and must be recreated if needed. Master-Detail Relationship (Parent Deleted): If a record is a child or detail in a master-detail relationship and the parent record is deleted, the child record is also soft del...