Posts

Showing posts from October, 2024

13 - Triggers BEST PRACTICES

 1) Dont write all code in Triggers but shift it in APEX Classes

12 - Order of Execution

Order   (Hint : Execution can restart for few records at few points . For more check : Reference - 166 / U /SDC) In Salesforce, the order of execution is important as it determines how records are processed and what actions are performed in response to different types of operations (insert, update, delete, etc.). Here’s a summary of the main steps in Salesforce's order of execution: System Validation Rules : Salesforce verifies that required fields have non-null values and that field formats are valid. Before Triggers : Executes "before" triggers, which allow you to set or modify values before the record is saved. System Validation Rules Again : Runs custom validation rules if the record is modified by a before trigger. Duplicate Rules : Checks for duplicates based on configured duplicate rules. Save Record (But Not Committed) : Saves the record to the database but does not commit. After Triggers : Executes "after" triggers, which allow for actions based on reco...

11 - Trigger : Part 3

 When to use After and Before How to decide : Trigger Type Use When You Need To... Typical Scenarios Before - Modify the same record' s fields before saving without a DML statement - Auto-populate or set default values - Validate data before it’s committed to the database - Enforce validation rules - Prevent DML with errors (addError() method) - Prevent record saving based on conditions After - Work with related records or perform actions needing record existence in the database - Update related records (like updating Account after Contact save) - Access fields only available after saving (like Id or RecordTypeId) - Perform complex logic needing committed data - Execute additional operations requiring DML (e.g., creating new records based on the saved record’s details) - Send notifications, make callouts This table can be a quick reference guide for choosing between before and after triggers based on your needs. Hint : Triggers are by default Bulkified . so if I have to execute 5...

10 - Trigger Part 2 : Trigger context variables

 In Salesforce, trigger context variables are special variables provided within Apex triggers that give access to the records and other information relevant to the operation that caused the trigger to fire. These context variables help developers handle different scenarios and ensure that triggers behave correctly based on the operation and its state.Here's a summary of the key trigger context variables: Context Variable Description Use Case Trigger.new Contains the list of new records that are entering the system (available for insert and update events). Modify fields on new records before they’re saved. Trigger.old Contains the list of the original versions of records (only available for update and delete events). Compare old and new field values in an update operation. Trigger.newMap Provides a map of IDs to the new versions of records (available for insert and update events). Access specific records by ID for easy reference. Trigger.oldMap Provides a map of IDs to the old vers...

9 - Triggers Part 1

 In Salesforce, triggers are pieces of Apex code that automatically execute before or after specific database operations, such as when a record is created, updated, deleted, or restored. Triggers allow developers to define custom logic that performs actions in response to these changes in the Salesforce database. Types of Triggers Before Triggers Executed before a record is saved to the database. Commonly used for validation and updating fields on records before they are saved. After Triggers Executed after a record is saved to the database. Used for actions that depend on the record ID or related records , such as creating related records, sending emails, or updating other records. Trigger Events Triggers can be set to execute on various events, such as: Before Insert : Runs before a new record is inserted. Before Update : Runs before an existing record is updated. Before Delete : Runs before a record is deleted. After Insert : Runs after a new record is inserted. After Update...

8 - Different Workflows in Salesforce

 BACKGROUND :  Different types of workflows in Salesforce In Salesforce, workflows help automate various business processes and tasks. Here are some common types of workflows used in Salesforce: 1. Workflow Rules Purpose: Automate standard internal procedures and processes to save time. Actions Available: Update fields, send email alerts, create tasks, and send outbound messages. Trigger: Changes to records that meet specified criteria. Limitations: Actions are limited, and they are relatively static; Workflow Rules are being phased out in favor of Flows. 2. Process Builder Purpose: Automate more complex business processes that need multiple steps or conditions. Actions Available: Update records, post to Chatter, invoke Apex, launch a flow, send an email alert, and more. Trigger: Record changes, Platform Events, or custom conditions. Use Case: Use when you need a process with multiple steps or complex criteria that Workflow Rules can't handle. 3. (Visual)  Flow Bu...

7 - SOQL : Aggregate functions

 SOQL : Aggregate functions Example : SELECT StageName, COUNT(Id), MIN(Amount), MAX(Amount), AVG(Amount) FROM Opportunity GROUP BY StageName Here's a tabular overview of SOQL aggregate functions: Aggregate Function Description Example Query COUNT() Counts the total number of records. SELECT COUNT() FROM Account WHERE Industry = 'Technology' COUNT(fieldName) Counts non-null values in a specified field. SELECT COUNT(Name) FROM Account WHERE Industry = 'Technology' SUM(fieldName) Calculates the total sum of a numeric field. SELECT SUM(Amount) FROM Opportunity WHERE StageName = 'Closed Won' AVG(fieldName) Calculates the average of a numeric field. SELECT AVG(Amount) FROM Opportunity WHERE StageName = 'Closed Won' MIN(fieldName) Returns the minimum value of a specified field. SELECT MIN(CloseDate) FROM Opportunity WHERE StageName = 'Closed Won' MAX(fieldName) Returns the maximum value of a specified field. SELECT MAX(CloseDate) FROM Opportunity WH...

6 - Object Relationships (Lookup and Master-Detail and Junction Objects)

 Here's a tabular comparison of the Lookup and Master-Detail relationship types in Salesforce: Feature Lookup Relationship Master-Detail Relationship Definition and Usage Loosely coupled; records are linked but can exist independently Tightly coupled; child record depends on the parent for existence Data Integrity and Ownership Child record does not inherit parent’s sharing or ownership Child inherits sharing, permissions, and ownership from the parent Roll-up Summary Fields Not available Available; aggregates values from child to parent Required Field Optional; child can exist without a parent Required; child must have a parent Cascade Delete Optional (not automatic) Automatic; deleting parent deletes all related child records Security and Access Child has independent sharing settings Child inherits sharing settings from the parent Hierarchy Depth Flexible; supports multi-level relationships Limited to strict parent-child hierarchy with up to two relationships This structure pro...

5 - Bulkification in Salesforce (Most Important)

Background Understanding ---> No, DML (Data Manipulation Language) and SOQL (Salesforce Object Query Language) are different in Salesforce: DML (Data Manipulation Language) : Used for modifying data in the database. DML operations include insert , update , delete , upsert , merge , and undelete . DML commands alter the state of the database by creating, updating, or removing records. SOQL (Salesforce Object Query Language) : Used specifically for querying data from the database. SOQL retrieves data but does not modify it. Common SOQL commands include SELECT , which fetches records based on specific criteria. What are Governer Limits Governor limits in Salesforce are enforced restrictions that help maintain system stability by preventing any single code execution from monopolizing shared resources. Since Salesforce operates on a multi-tenant architecture, these limits are crucial to ensuring fair resource allocation across all organizations using the platform. Key types of governo...

4 - Salesforce Tooling

1) Salesforce CLI from here https://developer.salesforce.com/tools/salesforcecli 2) Visual code Studio Learn Visual Studio Code in 7min (Official Beginner Tutorial) https://www.youtube.com/watch?v=B-s71n0dHUk 3) Install Salesforce Extension Pack Connecting the Org to Local VS Code View--> Command Pallet (Shift + Command + P in mac) SFDX : Salesforce Development Experience SFDX: Create a Project SFDX: Authorize an Org Check if connected : .sfdx --> sfdx-config.json (should show you the project  "defaultusername" : "ApexDevOrg" ) Bring code from Org to Local Check : force-app --> classes (Initially blank) Bring : Cloud symbol --> Apex classes --> click on the class (cloud symbol To Push code from Local to SF Org : Right click on the code --> SFDX:deploy this source to Org To Retrieve code from SF Org to local : Right click on the code --> SFDX:  Retrieve  this source from Org Autosave from local to Org :  

3 - DML

DML statements are INSERT / UPDATE / DELETE / UNDELETE TO DEBUG THE DML Check the Filter in the Execution Logs  INSERT the Object Class is copied from API Name // Inserting one single account Account acc = new Account(Name='CLR Infotech', Phone='9988998899'); acc.Rating = 'Hot'; insert acc; OR  create a list and do insert accounts OR // Alternate way to insert the accounts Database.insert(accounts, false);  You can use allorNone or false Database Methods vs. DML Statements in Salesforce: Feature Database Methods DML Statements Error Handling Supports partial success with allOrNone=false Entire transaction fails on any error Return Type Returns SaveResult/DeleteResult for each record Throws DmlException on failure Bulk Processing Suited for bulk processing with granular control Limited control, less suitable for bulk Usage in Triggers Preferred when selective transaction control needed Common for simpler trigger scenarios Performance Slightly slower due to added ...

2 - SOQL : Parent to Child Relationship Queries

SOQL : Parent to Child Relationship Queries FOR STANDARD OBJECTS ==>. **For Relationship Queries we need ---> Child Relationship Names which is found in the ---> Child ---> Field & Relationships ----> in Lookup (Datatype) --> click it --You get  Child Relationship Names // Get all related contacts of an account SELECT Name, Phone, Website, (SELECT Name, Department, Email FROM Contacts ) FROM Account FOR CUSTOM OBJECTS ==>. **For Relationship Queries we need ---> Child Relationship Names which is found in the ---> Child ---> Field & Relationships ----> in Lookup (Datatype) --> click it --You get  Child Relationship Names + (YOU ADD suffix __r in the  FOR CUSTOM OBJECTS==>. **For Relationship Queries we need ---> ) // Get all books(child object) of an author (parent object) SELECT Name, (SELECT Name FROM Books__r ) FROM Author__c RESULT CAN HAVE MULTIPLE CHILD RECORDS Limitations   Only one lev...

API Names in Salesforce

 In Salesforce, an API Name is a unique identifier for metadata components like fields, objects, or custom settings that enables external systems, scripts, and integrations to reference Salesforce data programmatically. The API name remains consistent, even if the label displayed in the user interface changes, making it essential for maintaining integration stability. Key Characteristics of API Names Field and Object API Names : Standard object and field API names generally mirror their label names, but with spaces removed. Custom fields and objects have the suffix __c , denoting them as custom. Example: A custom object called "Project" would have an API name of Project__c . A custom field called "Start Date" on the Project object would have an API name of Start_Date__c . Case-Sensitivity : API names in Salesforce are case-sensitive , so it’s essential to match them exactly when using them in code or integrations. Usage : API names are used in SOQL queries, Apex co...

1- Apex Testing and SOQL

 What to test  Single action Bulk action Positive action Negative action Restricted users (HINT:- write test cases with different positive and negative numbers as input) (HINT:- Sometimes the results are not expected so in that case change the original class )  **Minimum Test coverage in SF Apex is 75% **System.assert() etc but use Assert class for testing ----------------------------------------SOQL----------------------------------- IN , LIKE, LIMIT, OFFSET // Get latest 5 records and skip first 5 SELECT Name, Status, LeadSource, CreatedDate FROM Lead ORDER BY CreatedDate DESC LIMIT 5 OFFSET 5  Date Literals In SOQL, date literals make it easy to filter data based on dynamic or specific date ranges without having to calculate exact dates manually. These literals work with date, datetime, and time fields and are particularly useful in WHERE clauses. Here’s a breakdown of commonly used date literals in SOQL: Commonly Used Date Literals Today and Relative Days TODAY...