0% found this document useful (0 votes)
24 views2 pages

Triggers

The document outlines various Salesforce triggers and Apex classes for managing data operations such as preventing account insertions without names, updating related records, and logging deletions. It also includes examples of handling bulk updates, using helper classes for logic management, and firing custom events between Lightning components. Additionally, it describes a scheduled batch job for generating and emailing monthly sales reports.

Uploaded by

Shubham Gaikwad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views2 pages

Triggers

The document outlines various Salesforce triggers and Apex classes for managing data operations such as preventing account insertions without names, updating related records, and logging deletions. It also includes examples of handling bulk updates, using helper classes for logic management, and firing custom events between Lightning components. Additionally, it describes a scheduled batch job for generating and emailing monthly sales reports.

Uploaded by

Shubham Gaikwad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

1. Before Insert Trigger 2.

Before Update Trigger


Scenario: Prevent insertion of Accounts without a name. Scenario: Prevent updates to the Amount field in the Opportunity object if its Stage is
Closed Won.
trigger PreventAccountWithoutName on Account (before insert) {
for (Account acc : Trigger.new) { trigger PreventAmountUpdate on Opportunity (before update) {
if (acc.Name == null) { for (Opportunity opp : Trigger.new) {
acc.addError('Account Name cannot be blank.'); Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
} if (oldOpp.StageName == 'Closed Won' && opp.Amount != oldOpp.Amount) {
} opp.addError('Cannot update Amount for Closed Won Opportunities.');
} }
}
}
3. After Insert Trigger 4. After Update Trigger
Scenario: Create a Contact automatically when an Account is inserted. Scenario: Update a related Contact’s Email field when the related Account's Website
changes.
trigger CreateContactOnAccountInsert on Account (after insert) {
List<Contact> contactList = new List<Contact>(); trigger UpdateContactEmail on Account (after update) {
List<Contact> contactList = new List<Contact>();
for (Account acc : Trigger.new) {
Contact con = new Contact(LastName = acc.Name, AccountId = acc.Id); for (Account acc : Trigger.new) {
contactList.add(con); Account oldAcc = Trigger.oldMap.get(acc.Id);
} if (acc.Website != oldAcc.Website) {
for (Contact con : [SELECT Id, Email FROM Contact WHERE AccountId = :acc.Id]) {
if (!contactList.isEmpty()) { con.Email = '[email protected]'; // Example update
insert contactList; contactList.add(con);
} }
} }
}

if (!contactList.isEmpty()) {
update contactList;
}
}

5. Before Delete Trigger 6. After Delete Trigger


Scenario: Prevent deletion of an Account if it has related Contacts. Scenario: Log details in a custom object Account_Log__c when an Account is deleted.

trigger PreventAccountDeletion on Account (before delete) { trigger LogDeletedAccount on Account (after delete) {
for (Account acc : Trigger.old) { List<Account_Log__c> logList = new List<Account_Log__c>();
Integer contactCount = [SELECT COUNT() FROM Contact WHERE AccountId = :acc.Id];
if (contactCount > 0) { for (Account acc : Trigger.old) {
acc.addError('Cannot delete Account with associated Contacts.'); Account_Log__c log = new Account_Log__c(Name = acc.Name, Account_Id__c = acc.Id);
} logList.add(log);
} }
}
if (!logList.isEmpty()) {
insert logList;
}
}

Apex Class for Scheduled Sales Report: // Set up the email


This Apex Batch Job collects monthly sales performance data and emails the report to Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
managers email.setToAddresses(new String[]{'[email protected]'}); // Change to actual email
email.setSubject('Monthly Sales Report');
global class MonthlySalesReportBatch implements Database.Batchable<SObject>, email.setPlainTextBody(reportBody);
Schedulable {
// This method defines the records to be processed // Send the email
global Database.QueryLocator start(Database.BatchableContext BC) { Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
return Database.getQueryLocator( }
'SELECT Name, Amount, StageName, CloseDate ' +
'FROM Opportunity ' + // This method runs after all batches finish (can be used for logging, etc.)
'WHERE CloseDate = LAST_N_DAYS:30 ' + // Fetch Opportunities closed in the last 30 global void finish(Database.BatchableContext BC) {}
days
'ORDER BY Amount DESC' // Order by highest sales amount first // This method allows scheduling of the batch job
); global void execute(SchedulableContext SC) {
} MonthlySalesReportBatch batch = new MonthlySalesReportBatch();
// This method processes each batch of records Database.executeBatch(batch, 50); // Run batch with 50 records per batch
global void execute(Database.BatchableContext BC, List<Opportunity> scope) { }
// Prepare the email report }
String reportBody = 'Monthly Sales Report:\n\n';
How to Schedule the Job in Salesforce
for (Opportunity opp : scope) { Run this in Developer Console to schedule it:
reportBody += 'Deal: ' + opp.Name + ' | Amount: $' + opp.Amount + ' | Stage: ' +
opp.StageName + '\n'; System.schedule('Monthly Sales Report', '0 0 9 1 * ?', new MonthlySalesReportBatch());
}
7. Before Update - Handling Bulk Records (Best Practice) 8. Trigger on Custom Object
Scenario: Automatically populate the Industry field with Technology if it's blank during Scenario: When a new Order__c is inserted, update the Total_Orders__c field on related
update. Account.

trigger UpdateIndustry on Account (before update) { trigger UpdateTotalOrders on Order__c (after insert) {
for (Account acc : Trigger.new) { Map<Id, Account> accMap = new Map<Id, Account>();
if (acc.Industry == null) {
acc.Industry = 'Technology'; for (Order__c ord : Trigger.new) {
} if (ord.Account__c != null) {
} if (!accMap.containsKey(ord.Account__c)) {
} accMap.put(ord.Account__c, new Account(Id = ord.Account__c));
}
}
}

if (!accMap.isEmpty()) {
for (Account acc : [SELECT Id, Total_Orders__c FROM Account WHERE Id IN
:accMap.keySet()]) {
acc.Total_Orders__c = (acc.Total_Orders__c != null ? acc.Total_Orders__c : 0) + 1;
accMap.put(acc.Id, acc);
}
update accMap.values();
}
}

9. Trigger to Call a Helper Class (Best Practice) 10. Trigger with Future Method
Scenario: Use a handler class to manage logic for inserting Contacts when an Account is Scenario: Send an email when a Case is closed.
inserted.
trigger CaseClosedTrigger on Case (after update) {
trigger AccountTrigger on Account (after insert) { for (Case c : Trigger.new) {
AccountTriggerHandler.createContacts(Trigger.new); if (c.Status == 'Closed' && Trigger.oldMap.get(c.Id).Status != 'Closed') {
} EmailHandler.sendCaseClosureEmail(c.Id);
}
Handler Class: }
}
public class AccountTriggerHandler {
public static void createContacts(List<Account> accList) { Email Handler Class:
List<Contact> contactList = new List<Contact>();
public class EmailHandler {
for (Account acc : accList) { @future
Contact con = new Contact(LastName = acc.Name, AccountId = acc.Id); public static void sendCaseClosureEmail(Id caseId) {
contactList.add(con); Case c = [SELECT Id, Contact.Email FROM Case WHERE Id = :caseId];
} if (c.Contact.Email != null) {
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
if (!contactList.isEmpty()) { email.setToAddresses(new String[]{c.Contact.Email});
insert contactList; email.setSubject('Your Case has been Closed');
} email.setPlainTextBody('Dear Customer, your case has been closed. Thank you!');
} Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
} }
}
}
******How to fire custom event*****
1. Child Component (childComponent.js) 2. Parent Component (parentComponent.js)
javascript javascript

import { LightningElement } from 'lwc'; import { LightningElement } from 'lwc';

export default class ChildComponent extends LightningElement { export default class ParentComponent extends LightningElement {
handleClick() { handleCustomEvent(event) {
// Creating a custom event with name 'customclick' alert(event.detail.message); // Display the message from the child
const event = new CustomEvent('customclick', { }
detail: { message: 'Hello from Child Component' } }
});
Parent Component HTML (parentComponent.html)
// Dispatching the event html
this.dispatchEvent(event); <template>
} <c-child-component oncustomclick={handleCustomEvent}></c-child-component>
} </template>

Child Component HTML (childComponent.html)


html

<template>
<lightning-button label="Click Me" onclick={handleClick}></lightning-button>
</template>

You might also like