Remote Call-In (Integration design pattern)

Remote system make callout in salesforce to create, retrieve, update, or delete records. Solutions: Salesforce provides a SOAP/REST API that remote systems can use to: The client executing SOAP/REST API must have a valid login and obtain a session to perform any API calls. The API respects object-level and field-level security configured in Salesforce based onContinue reading “Remote Call-In (Integration design pattern)”

Batch Data Synchronization (Integration design pattern)

Data Replication/Synchonization between systems which is done in a batch manner. Solutions: Salesforce Change Data Capture publishes change events, which represent changes to Salesforce records. With Change Data Capture, you can receive near-real-time changes of Salesforce records, and synchronize corresponding records in an external data store. Change Data Capture takes care of the continuous synchronizationContinue reading “Batch Data Synchronization (Integration design pattern)”

Fire and Forget (Integration design pattern)

In this integration pattern, Salesforce calls the remote system, but doesn’t wait for the call’s successful completion. Solutions: No customization is required in Salesforce to implement platform events. This is the recommended solution when the remote process is invoked from an insert or update event. External apps can listen to event messages by subscribing toContinue reading “Fire and Forget (Integration design pattern)”

Display Alert when Laptop is fully charged

You can display standard warning message when your laptop battery becomes low beyond threshold level but reverse is not true. It would be better if there would be in-built solution to display warning when laptop battery becomes full so that we can switch-off the power button which would increase the laptop battery life. Since thereContinue reading “Display Alert when Laptop is fully charged”

Request and Reply (Integration design pattern)

In this Integration pattern, Salesforce need to wait for response to complete the process. Solutions: Point & Click based integration from Lightning Flow. External System should provide Open API or should have extragent schema. Click this for trailhead Exercise. Salesforce enables you to consume a WSDL and generate a resulting proxy Apex class. A user-initiatedContinue reading “Request and Reply (Integration design pattern)”

Bulk State Transition (Apex Design Patterns)

What is Bulk State Transition?: This pattern is used to perform bulk actions efficiently based on change of state of one or more records. Why Bulk State Transition?: We generally creates a utility to process bulk records here. Same utility can be used anywhere irrespective of triggers. Problem: We will taking an example of orderContinue reading “Bulk State Transition (Apex Design Patterns)”

Composite Design Pattern (Apex Design Patterns)

What is Composite Design Pattern?: Composite is a structural design pattern that lets you compose objects into tree structures and then work with these structures as if they were individual objects. Composite design pattern treats each node in two ways:1) Composite – Composite means it can have other objects below it.2) leaf – leaf means it has no objects below it.Continue reading “Composite Design Pattern (Apex Design Patterns)”

Facade Design Pattern (Apex Design Patterns)

What is Facade Pattern?: This is a structure design pattern which hides the complexity of the system and provides simple interface to the client. This pattern involves a class called as Facade which provides simplified methods required by clients and delegates its call to methods of existing classes. Why Facade?: There may be many complexContinue reading “Facade Design Pattern (Apex Design Patterns)”

Decorator Design Pattern (Apex Design Patterns)

What is Decorator Pattern?: Decorator pattern allows a user to add new functionality to an existing object without altering its structure. This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class. This pattern creates a decorator class which wraps the original class and provides additional functionalityContinue reading “Decorator Design Pattern (Apex Design Patterns)”

Strategy Design Pattern (Apex Design Patterns)

What is Strategy Pattern?: Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable. The Strategy pattern (aka the policy pattern) attempts to solve the issue where you need to provide multiple solutions for the same problem so that oneContinue reading “Strategy Design Pattern (Apex Design Patterns)”

Singleton Design Pattern (Apex Design Patterns)

What is singleton?: Its a design pattern which restricts the instantiation of a class to one “single” instance only within a single transaction context. Why Singleton?: minimizing object instantiation for improved performance and to mitigate impact of governor limits Let’s discuss problem first then solution using singleton pattern- Problem: So in above example, if the record areContinue reading “Singleton Design Pattern (Apex Design Patterns)”

Apex Design Patterns

Developers around the world over the period of time invented some patterns (repeatable solutions) to solve some common occurring problems, we call it design patterns. We are working on multi tenant architecture in salesforce, all design patterns don’t work here. We have some tricky patterns here in Apex because of this architecture, we call itContinue reading “Apex Design Patterns”

Dynamic Forms in Salesforce Lightning

Sometimes there is a requirement where you want to show/hide certain fields based on some criteria but that was not possible with standard salesforce layout and thats why dynamic forms came into picture. With dynamic forms we can customize highlighted panel and the detail view of the record page. On the highlighted panel, you canContinue reading “Dynamic Forms in Salesforce Lightning”

QR Code Scanner in Salesforce

Currently we have in-built QR code scanner in Salesforce. But problem with this scanner is that it only supports salesforce mobile app and some clients wants to use scanner through desktop browser which can scan QR Code using any camera attached to the desktop. So I have found a custom solution for this so thatContinue reading “QR Code Scanner in Salesforce”

Create your own Launch pad in Salesforce Lightning

Like App Launcher, Launchpad lets user quickly access the information they need. Using launchpad, you can access visualforce pages, lightning web components, lightning components directly without creating any tab. There is a standard lightning component named as ‘LaunchPad’ which can use on following lightning pages- Home Page Record Page App Page Approach is simple toContinue reading “Create your own Launch pad in Salesforce Lightning”

How to access custom attributes from an event object

You can use following two approach to access attribute value from event object- Approach 1 – Retrieve using standard Attribute: Here we can use name attribute. We access the attribute value using event.target.{attribute name}. Check printNameAttribute method in below code which retrieves value from Name attribute. Approach 2 – Retrieve using Custom Attribute: Here weContinue reading “How to access custom attributes from an event object”

Creating a record using Rest Explorer(Workbench) in Salesforce

I hope you are comfortable with rest api. So if you want to access/update the salesforce data, you can do that using standard salesforce rest api end point. So if you want to test this end point for data access/update, you can test that using workbench which is very simple and straigh-forward way. So let’sContinue reading “Creating a record using Rest Explorer(Workbench) in Salesforce”

Check Salesforce organization limits and usage using Workbench

Ensure you are logged into the organization where you want to verify your limits. Navigate to: https://workbench.developerforce.com/login.php Accept any oauth prompts to complete authentication On the ‘Jump to’ picklist select REST Explorer. Click Select. From the options presented select: /services/data/vXX.0/limits Click Execute. Select the SingleEmail area to view the daily maximum and remaining calls. Reference:Continue reading “Check Salesforce organization limits and usage using Workbench”

Enforce Security With the stripInaccessible Method

Use the stripInaccessible method to enforce field- and object-level data protection. This method can be used to strip the fields and relationship fields from query and subquery results that the user can’t access. The method can also be used to remove inaccessible sObject fields before DML operations to avoid exceptions and to sanitize sObjects that have beenContinue reading “Enforce Security With the stripInaccessible Method”

Use the Safe Navigation Operator to Avoid Null Pointer Exceptions

Use the safe navigation operator (?.) to replace explicit, sequential checks for null references. This operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a NullPointerException. If the left-hand-side of the chain expression evaluates to null, the right-hand-side is not evaluated. Use the safe navigation operator (?.) in method, variable, andContinue reading “Use the Safe Navigation Operator to Avoid Null Pointer Exceptions”

How to use Apex Replay Debugger

Step 1. Use the Debug: Toggle Breakpoint and SFDX: Toggle Checkpoint commands to toggle on and off breakpoints and checkpoints, respectively Step 2.  Use SFDX: Update Checkpoints in Org command to update checkpoint in the org. You must tell Salesforce about your checkpoints so that heap dumps are collected as your Apex code executes Notes:Continue reading “How to use Apex Replay Debugger”

Creating LWC project using CLI

Step 1. Create a new Salesforce project with this commandsfdx force:project:create -n projectName Step 2. Navigate to the directory with this commandcd projectName Step 3. Authorize an org with this commandsfdx force:auth:web:login -s -a projectName In this step, browser will open, you need to enter credentials to authorize your org with this project. You can closeContinue reading “Creating LWC project using CLI”

Build an Aura Component to Override a Standard Action

Topics to learn-1. How to populate picklist values in a field.2. How to use modal to show popup3. Use of slds-backdrop class4. How to use LDS (lightning data service) to create/edit a record. Please refer the below code to learn the above topics- PropertyDialog.cmp <force:recordData aura:id="forceRecord"                   Continue reading “Build an Aura Component to Override a Standard Action”

LWC publish subscribe model

To understand this concept, please go through this trailhead-https://trailhead.salesforce.com/content/learn/projects/lwc-build-flexible-apps/inter-comp-events?trail_id=build-lightning-web-components pubsub.js /**  * A basic pub-sub mechanism for sibling component communication  *  * TODO – adopt standard flexipage sibling communication mechanism when it’s available.  */ const events = {}; const samePageRef = (pageRef1, pageRef2) => {     const obj1 = pageRef1.attributes;     const obj2 = pageRef2.attributes;     return Object.keys(obj1)         .concat(Object.keys(obj2))         .every(key => {             return obj1[key] === obj2[key];         }); }; /**  * Registers a callback for an event  * @param {string} eventName – Name of the event to listen for.  * @param {function} callback – Function to invoke when said event is fired.  * @param {object} thisArg – The value to be passed as the this parameter to the callback function is bound.  */ const registerListener = (eventName, callback, thisArg) => {     // Checking that the listener has a pageRef property. We rely on that property for filtering purpose in fireEvent()     if (!thisArg.pageRef) {         throw new Error(             ‘pubsub listeners need a “@wire(CurrentPageReference) pageRef” property’,         );     }     if (!events[eventName]) {         events[eventName] = [];     }     const duplicate = events[eventName].find(listener => {         return listener.callback === callback && listener.thisArg === thisArg;     });     if (!duplicate) {         events[eventName].push({ callback, thisArg });     } }; /**  * Unregisters a callback for an event  * @param {string} eventName – Name of the event to unregister from.  * @param {function} callback – Function to unregister.  * @param {object} thisArg – The value to be passed as the this parameter to the callback function is bound.  */ const unregisterListener = (eventName, callback, thisArg) => {Continue reading “LWC publish subscribe model”

Make Long-Running Callouts with Continuations

Use the Continuation class in Apex to make a long-running request to an external Web service. Process the response in a callback method. An asynchronous callout made with a continuation doesn’t count toward the Apex limit of 10 synchronous requests that last longer than five seconds. To make a long-running callout, define an Apex method that returnsContinue reading “Make Long-Running Callouts with Continuations”

Resolution for SVG rendering issue on visualforce page

Issue: Using tag to get SLDS Icons in vf. Initially on page load all works fine but when I try to re-render any that have icons inside it, on complete of rerendering it vanish my all icons. Resolution:  I was able to overcome the problem of SVG images disappearing using following steps- -Add docType=”html-5.0″ attributeContinue reading “Resolution for SVG rendering issue on visualforce page”

Convert old Notes into Enhanced Notes using Apex

When you convert Old Notes to enhanced Notes, following must be kept in mind-1. CreatedDate/LastModifiedDate of the enhanced note must be same that of the old Note. Create a permission set for that. Follow the steps to create the same- From Setup, enter Permission Sets in the Quick Find box, then select Permission Sets. CreateContinue reading “Convert old Notes into Enhanced Notes using Apex”

Deleting Files related to a record

Sample Code:         Set contentDocumentIds = new Set();        List cDocLink = [Select id, ContentDocumentId from                                              ContentDocumentLink where LinkedEntityId = :ParentId];        for(ContentDocumentLink contentDocLinks : cDocLink)Continue reading “Deleting Files related to a record”

Converting attachment into file

When you convert attachment to File, following must be kept in mind-1. Filename should be without extension. It can be with extension but its better to without extension.2. CreatedDate/LastModifiedDate of the file must be same that of the attachment. Create a permission set for that. Follow the steps to create the same- From Setup, enterContinue reading “Converting attachment into file”

Mass action for Visualforce & lightning

We are deleting multiple records using mass action here. After deleting we are redirecting back to the same list view.  Please follow following four steps to create mass action button- Step1. Create a extension with standardsetController Step2. Create a vf page with recordSetVar attribute Step3. Create a list button for this vf. Step4. Add thisContinue reading “Mass action for Visualforce & lightning”

How to navigate from one component to other component in lightning

We will use lightning:navigation component to navigate to other component. Please follow below steps for the same- Step 1.  Add the lightning:isUrlAddressable interface to the component on which you want to navigate. for eg.             {!v.dummyValue}. Step 2. Retrieve the attribute values from the page state. In below code, ‘c__dummyString’Continue reading “How to navigate from one component to other component in lightning”

Standard New and Edit functionality

public with sharing class ReadingPermissionController { public ReadingPermission__c newReadingPermission {get;set;} public String returnUrl {get;set;} public ReadingPermissionController(ApexPages.StandardController setCon) { ReadingPermission__c r = (ReadingPermission__c) setCon.getRecord(); newReadingPermission = new ReadingPermission__c(); if(r.Id != null) { newReadingPermission = [Select Id, Name, Permission_Holder_Name__c, Permission_Holder_ID__c, Permission_Holder_Type__c, Granted_Permissions__c from ReadingPermission__c where id =: r.Id]; } //system.assert(false, newReadingPermission ); returnUrl = apexpages.currentPage().getParameters().get(‘retURL’); } publicContinue reading “Standard New and Edit functionality”

Creating Vf and Apex Class for Portal

Class- public with sharing class ReadingPermissionController { public ReadingPermission__c newReadingPermission {get;set;} public String returnUrl {get;set;} public ReadingPermissionController(ApexPages.StandardController setCon) { ReadingPermission__c r = (ReadingPermission__c) setCon.getRecord(); newReadingPermission = new ReadingPermission__c(); if(r.Id != null) { newReadingPermission = [Select Id, Name, Permission_Holder_Name__c, Permission_Holder_ID__c, Permission_Holder_Type__c, Granted_Permissions__c from ReadingPermission__c where id =: r.Id]; } //system.assert(false, newReadingPermission ); returnUrl = apexpages.currentPage().getParameters().get(‘retURL’); }Continue reading “Creating Vf and Apex Class for Portal”

Salesforce Interview Questions

How can we improve VisualForce Page Performance?Hint:- 1. Reduce view state2. Reduce load time3. Careful use of multiple concurrent requests4. Queries and security- using with sharing keyword5. Preventing field values from dropping off the page. For more information, please open following link-http://www.salesforce.com/docs/developer/pages/Content/pages_best_practices_performance.htm What is View state? How can we reduce this?Visualforce pages that contain aContinue reading “Salesforce Interview Questions”

How to work efficiently with DML statements in Apex class

The following Apex DML statements are available:InsertUpdateUpsertDeleteUndeleteMerge Salesforce allows only 150 DML statements for each Apex transaction. So its better to check the list against null or empty before performing DML operations.  Example- Account a = new Account(Name=’Acme2′);insert(a);Account myAcct = [SELECT Id, Name, BillingCity FROM Account WHERE Id = :a.Id];myAcct.BillingCity = ‘San Francisco’; try {Continue reading “How to work efficiently with DML statements in Apex class”

Maintaining Width of multi-picklist on visualforce page in Salesforce

Use following javascript code $(document).ready(function(){ $(“[id*=’_unselected’]”).dblclick(function(){ setTimeout(function() { $(“[id*=’_unselected’]”).removeAttr(‘style’); $(“[id*=’_selected’]”).removeAttr(‘style’); }, 100); }); $(“[id*=’_selected’]”).dblclick(function(){ setTimeout(function() { $(“[id*=’_unselected’]”).removeAttr(‘style’); $(“[id*=’_selected’]”).removeAttr(‘style’); }, 100); }); $(“[title=’Add’]”).click(function(){ setTimeout(function() { $(“[id*=’_unselected’]”).removeAttr(‘style’); $(“[id*=’_selected’]”).removeAttr(‘style’); }, 100); }); $(“[title=’Remove’]”).click(function(){ setTimeout(function() { $(“[id*=’_unselected’]”).removeAttr(‘style’); $(“[id*=’_selected’]”).removeAttr(‘style’); }, 100); });});

Getting Dynamic Initialized recordList

public class RecordListUtility { public static String getIntializedRecordList(String objectName, Set fieldNames, String listVariable, Integer limitRows) { String sqlString = ‘Select ‘; for(String field : fieldNames) { sqlString += field + ‘, ‘; } sqlString = sqlString.substring(0, sqlString.length() – 2); sqlString += ‘ from ‘ + objectName + ‘ limit ‘+ limitRows; List objectRecordList = Database.Query(sqlString);Continue reading “Getting Dynamic Initialized recordList”

Creating portal user through trigger

Portal user will be created if unique email is inserted in contact.If user is already created, no new portal user will be created for that contact. trigger CreatePortalUser on Contact (after insert, after update) { List usersToInsert = new List(); List ExistingUsers = [Select contactId from User where contactId in: Trigger.NewMap.keySet()]; Set contactsHavingUsers = newContinue reading “Creating portal user through trigger”

Getting Where condition string for filtering specific object records

Below is the function and wrapper class which can be used to get where condition. This function can be customized as per different requirement. //Returns wherecondition for soql based on SearchFieldWrapper class list which can be used on visual force page for filter functionality.public String getWhereCondition (List searchFieldWrapperList) { String whereCondition = ”; for (WrapperClassContinue reading “Getting Where condition string for filtering specific object records”

Getting customfieldtype based on field display type

We will use customfieldtype later to generate dynamic query from list of fields of specific object. public String getCustomFieldType(Schema.DisplayType fieldType) { String customFieldType; Set stringTypes = new Set(); stringTypes.add(Schema.DisplayType.Reference); stringTypes.add(Schema.DisplayType.ID); stringTypes.add(Schema.DisplayType.String); stringTypes.add(Schema.DisplayType.Email); stringTypes.add(Schema.DisplayType.URL); stringTypes.add(Schema.DisplayType.Picklist); stringTypes.add(Schema.DisplayType.Phone); Set numberTypes = new Set(); numberTypes.add(Schema.DisplayType.Double); numberTypes.add(Schema.DisplayType.Percent); numberTypes.add(Schema.DisplayType.Integer); numberTypes.add(Schema.DisplayType.Currency); if(fieldType == Schema.DisplayType.MultiPicklist) { customFieldType = ‘str’; } else if(stringTypes.contains(fieldType)) {Continue reading “Getting customfieldtype based on field display type”

Getting operator list based on field display type

Below is the function which you can include in any of the class where you want to return operator list based on field type. public List getOperatorList(Schema.DisplayType fieldType) { List operatorList = new List(); operatorList.add(new SelectOption(”, ‘–None–‘)); Set stringTypes = new Set(); stringTypes.add(Schema.DisplayType.Reference); stringTypes.add(Schema.DisplayType.ID); stringTypes.add(Schema.DisplayType.String); stringTypes.add(Schema.DisplayType.Email); stringTypes.add(Schema.DisplayType.URL); stringTypes.add(Schema.DisplayType.Picklist); stringTypes.add(Schema.DisplayType.Phone); Set numberTypes = new Set(); numberTypes.add(Schema.DisplayType.Double);Continue reading “Getting operator list based on field display type”