Posts

Showing posts with the label Apex

Five-Level Parent-to-Child Relationship SOQL Queries in Apex

Apex now supports traversing up to five levels of parent-child records with SOQL relationship queries. Each subquery counts towards the aggregate queries processed in an SOQL query statement. Starting from API version 61.0, SOQL parent-child relationship queries in Apex can be structured such that the first level of the query is a parent root, and child relationships can be queried up to four levels deep from the parent root. You can keep track of the number of aggregate queries processed in an SQL statement using the Limits.getAggregateQueries() method. The Limits.getLimitAggregateQueries() method returns a value of 300, the total number of aggregate queries that can be processed with SOQL query statements. This change applies to all editions. Below is an example of a Salesforce SOQL query statement with five levels of parent-child relationships. List<Account> accts =  [SELECT Name,     (SELECT LastName,         (SELECT AssetLevel,    ...

Use Apex Cursors for Expanded SOQL Query Result Support

Apex cursors allow you to process large query results without returning the entire result set in a single transaction. With cursors, you can traverse query results in parts and navigate forward and back. This makes it easier for developers to work with high-volume and resource-intensive jobs. Cursors are a great alternative to batch Apex as they can be used in a chain of queueable Apex jobs and are more powerful in many ways. They are especially useful for package and advanced developers who regularly work with large query result sets. NOTE: This feature is a Beta Service, which applies to all the salesforce editions. Apex cursors are stateless and generate results from the offset specified in the Cursor. fetch(integer position, integer count) method. You must track the offsets or positions of the results within your particular processing scenario. A cursor is created when a SOQL query is executed on a Database.getCursor() or Database.getCursorWithBinds() call. When a Cursor. fetch(...

Find Case ThreadId using Apex and Formulas

Ensure that an email sent to your customer support email is attached to an existing case using Thread ID. Formula - "ref:_" & LEFT($Organization.Id,5) & RIGHT($Organization.Id,5) & "._" & LEFT(Id,5) & SUBSTITUTE(Left(RIGHT(Id,10), 5), "0", "") & RIGHT(Id,5) & ":ref" Apex -  ref:_'+ UserInfo.getOrganizationId().left(5) + UserInfo.getOrganizationId().mid(11,4) + '._'+ caseId.left(5)+ caseId.mid(10,5) + ':ref ]'; The actual extraction of the thread ID is looking for anything in between "ref:" and ":ref" Example of a thread id: ref:_00D30oKPx._50030bwIii:ref Note: If multiple thread IDs are included in the header or the body of the email sent, the email will attach to the Case that is represented by the first thread ID in the string: Example  [ ref:_00D30oKPx._50030bwIii:ref ] [ ref:_00D30oKPx._50030bMuaN:ref ]  the email will attach to the case represented by ref:_00D30oKP...

Enum in Apex

In Apex, enums (enumerations) are a particular type that defines a set of named constants. Enums help represent fixed sets of related values, providing clarity, type safety, and ease of maintenance in your code. Salesforce supports enums in Apex, allowing developers to define custom data types with predefined values. Here's how you can define and use enums in Salesforce Apex: Syntax for Enum Declaration: public enum PartnerType {     SILVER,     GOLD,     PLATINUM } Usage Examples: Declaring Enum Variables: PartnerType status = PartnerType. SILVER; Switch Statements: switch(status) {     case PartnerType. SILVER:         // Do something         break;     case PartnerType. GOLD:         // Do something else         break;     default:         // Default case } Iterating Over Enum Values: for (PartnerType p : P...

Salesforce custom label in Apex, Visualforce, AURA, LWC

Salesforce custom labels can be used across different Salesforce technologies, including Apex, Visualforce, Aura components, and Lightning Web Components (LWC). Here's how you can use custom labels in each of these contexts: Apex : In Apex, you can access custom labels using the System.Label global variable. Custom labels are referenced by their developer name. String labelValue = System.Label.MyCustomLabel; Visualforce : In Visualforce pages, you can reference custom labels using the $Label global variable. <apex:outputText value="{!$Label.MyCustomLabel}" /> Aura Components: In Aura components, you can access custom labels using the $Label global value provider. <aura:component>     <aura:attribute name="labelValue" type="String" default="{!$Label.MyCustomLabel}" /> </aura:component> Lightning Web Components (LWC): In Lightning Web Components, you can import and reference custom labels using the @salesforce/label scop...

Getting Started with Apex

Image
What is Apex ?  Apex, a strongly typed, object-oriented programming language, empowers developers to execute flow and transaction control statements on the Salesforce servers in conjunction with calls to the API. It's a proprietary language developed by Salesforce, specifically designed to enable the creation of robust business logic within the Salesforce platform. With its syntactical similarity to Java, Apex serves as the backend code that can manipulate data in Salesforce, execute complex validation rules, and automate intricate business processes. Critical features of Apex include: Integration with Salesforce Data : Apex allows you to write complex queries and transactions against the data stored in Salesforce. Transactional Control: Operations in Apex are transactional, meaning that all DML operations can be rolled back if any error occurs during the transaction process. Governor Limits: Salesforce imposes runtime limits, known as governor limits, to ensure that runaway Apex...

Obtain the name of the SObject from a given record ID

In Apex, you can obtain the name of the SObject from a given record ID using the getSObjectType () method provided by the Id class. Example Id recordId = '001XXXXXXXXXXXX'; // Replace this with the actual record ID // Get the SObject type from the record ID Schema.SObjectType sObjectType = recordId.getSObjectType(); // Get the name of the SObject String sObjectName = sObjectType.getDescribe().getName(); System.debug('SObject Name: ' + sObjectName); In this example: recordId.getSObjectType() returns the Schema.SObjectType of the object associated with the record ID. sObjectType.getDescribe().getName() retrieves the name of the SObject. This approach allows you to dynamically determine the SObject name from a record ID in your Apex code.

Basic overview of Apex classes, variables, constructors, and methods in Salesforce

Apex is a strongly-typed, object-oriented programming language that allows developers to write custom business logic and perform complex operations on Salesforce data. Let's go through the basic components of an Apex class, including variables, constructors, and methods. Apex Class: An Apex class is a blueprint for creating objects in Salesforce. It defines the structure and behavior of objects by encapsulating data and methods.  Here's a simple example of an Apex class: public class MyClass {     // Variables     public String name;     public Integer age;          // Constructor     public MyClass(String n, Integer a) {         name = n;         age = a;     }          // Method     public void displayInfo() {         System.debug('Name: ' + name);         System.debug('Age: ' + age);   ...

@TestVisible Annotation in Apex

In Salesforce, the @TestVisible annotation makes private or protected variables and methods visible in test classes. This annotation allows you to access and manipulate these elements for testing purposes without changing their access modifiers, thereby maintaining encapsulation and security in production code while enabling thorough testing. Here is an example  public class MyClass {     // Private member variable     @TestVisible private Integer myPrivateVariable = 09; } @isTest  private class TestVisibleClassTest {     @isTest static void testExample() {         // Access private variable annotated with TestVisible         Integer i = MyClass. myPrivateVariable;         System.assertEquals(09, i);     }  } Here are the key points about the @TestVisible annotation: Visibility : @TestVisible makes private or protected variables, properties, and methods visible in test...

@testSetup annotation in Apex

In Salesforce, the @ testSetup annotation is used in Apex tests to create test data that can be reused across multiple test methods within the same test class. This annotation is especially useful for making common test data required for various test methods, reducing redundancy, and improving test efficiency. Here's an example of how you can use the @ testSetup method in Salesforce: @isTest private class MyTestClass {          // Define test data setup method     @testSetup     static void setupTestData() {         // Create test records         Account acc = new Account(Name='Test Account');         insert acc;                  Contact con = new Contact(LastName='Test Contact', AccountId=acc.Id);         insert con;                  // You can create more test records as ...

Trigger Logic with Apex Switch

Switch Statements Apex provides a switch statement that tests whether an expression matches one of several values and branches accordingly. Switch Statements Rethink Trigger Logic with Apex Switch Trigger Context Variables The context variable Trigger.operationType is used to get the current System.TriggerOperation enum value. The following are the values of the System.TriggerOperation enum: AFTER_DELETE AFTER_INSERT AFTER_UNDELETE AFTER_UPDATE BEFORE_DELETE BEFORE_INSERT BEFORE_UPDATE trigger customerTrigger on Account (before insert, after insert) { switch on Trigger.operationType { when BEFORE_INSERT { System.debug('Before Insert'); } when AFTER_INSERT { System.debug('After Insert'); } when else { System.debug('Something went wrong'); } } }

Managed vs Unmanaged in Salesforce

Image
Managed Packages in Salesforce are a way for developers to package and distribute their custom applications and components to other Salesforce organizations. These packages encapsulate custom objects, fields, Apex code, Visualforce pages, Lightning components, and other metadata components developed on the Salesforce platform. Unmanaged packages in Salesforce are collections of metadata components that are bundled together for distribution and deployment. Unlike managed packages, which provide IP protection and versioning capabilities, unmanaged packages are primarily used for sharing customizations within a single Salesforce organization or for simple deployments.  Here is a comparison between Managed and Unmanaged packages. Managed Packages: Packaging and Distribution: Managed packages are packaged and distributed by Salesforce developers or ISVs (Independent Software Vendors) through the Salesforce AppExchange or other distribution channels. Developers can package custom object...

Pagination in Visualforce using StandardSetController

Image
The StandardSetController is a controller class that enables you to create a Visualforce page to showcase a list of records. It has built-in capabilities to handle pagination, thus simplifying displaying extensive data sets on a Visualforce page. Here are some key features and functionalities of StandardSetController: Pagination : StandardSetController automatically handles pagination, allowing you to display a subset of records on each page. It provides methods for navigating between pages, such as first(), previous(), next(), and last(). Sorting and Filtering : StandardSetController allows you to specify sorting and filtering criteria for the records displayed on the Visualforce page. You can define sorting order and filter conditions using the setSortOrder() and setFilterId() methods. Record Navigation : You can easily navigate to the first, last, previous, or next page of records using methods provided by StandardSetController. This simplifies the implementation of navigation contr...

Process Builder Bulkified

To create a bulkified process in Process Builder using an Apex class, we'll need to ensure that the Apex class and the invocable method within it are capable of handling bulk records efficiently. Example public class MyBulkifiedClass {     @InvocableMethod(label='Process Bulk Records' description='Process bulk records efficiently')     public static void processBulkRecords(List<MyObject__c> records) {         // Your bulkified logic here         List<SomeOtherObject__c> objectsToUpdate = new List<SomeOtherObject__c>();                  // Iterate over the input records         for (MyObject__c record : records) {             // Perform your business logic on each record             SomeOtherObject__c relatedObject = new SomeOtherObject__c();             rela...

Best practices for writing test classes in Salesforce

Writing effective test classes is crucial in Salesforce development to ensure the quality and stability of your code. Cover as many lines of code as possible. Testing Best Practices Code Coverage Best Practices Here are some best practices for writing test classes in Salesforce: Test Coverage: Aim for high code coverage, typically aiming for at least 75% coverage for your Apex classes, and 100% if possible. Ensure that your test methods exercise all code paths, including positive and negative scenarios. Isolation : Write tests that are isolated from each other and from the data in the organization. Use the @testSetup annotation to create test data once and reuse it across test methods, minimizing the need to insert duplicate data in each test method. Data Creation : Create the necessary test data within your test class using Apex code rather than relying on existing data in the organization. This ensures that your tests are self-contained and portable, independent of changes in th...

Apex Triggers in Salesforce

Image
In Salesforce, a trigger is a piece of Apex code that executes before or after specific data manipulation events occur, such as inserting, updating, deleting, or undeleting records. Triggers enable you to perform custom actions or validations when these events take place on Salesforce records. Refer to the below links for more details - Get Started with Apex Triggers Apex Triggers Define Apex Triggers Here are some key points about triggers in Salesforce: Execution Context: Triggers execute in response to specific database events and run in the Salesforce environment. Supported Events : Triggers can be defined to execute before or after specific events, including insert, update, delete, undelete, and upsert. Object-Specific: Triggers are associated with specific Salesforce objects, such as Accounts, Contacts, Opportunities, etc. Each trigger operates on records of its associated object type. Apex Language: Triggers are written in Apex, Salesforce's proprietary programming langua...