Menu Bar

Wednesday, 10 September 2025

Mastering LWC Debugging: A Step-by-Step Guide

Debugging is an essential skill for any Salesforce developer working with Lightning Web Components (LWC). JavaScript, being a case-sensitive language, can often lead to errors that are tricky to identify. In this blog, we’ll explore the best practices, tools, and techniques to debug LWC components effectively. Whether you’re a beginner or an experienced developer, this guide will help you streamline your debugging process.


Why Debugging LWC is Important

LWC components rely heavily on JavaScript, and even minor issues like variable case mismatches can cause errors. Debugging helps you identify and resolve these issues efficiently, ensuring your components function as expected. In this blog, we’ll cover:

  • Configurations to simplify debugging.
  • Browser and Salesforce settings for better performance.
  • Techniques to debug JavaScript and wire decorators.
  • Real-world debugging scenarios.

1. Enable Debug Mode in Salesforce

The first step in debugging LWC components is enabling debug mode. This makes it easier to debug JavaScript code by providing detailed logs.

Steps to Enable Debug Mode:

  1. Navigate to Setup in Salesforce.
  2. Search for Debug Mode.
  3. Enable debug mode for specific users who are actively debugging.
  4. Important: Only enable debug mode in developer sandboxes or developer orgs, as it can impact performance.

2. Disable Cache for Effective Debugging

Caching can cause issues during development, as changes in your code may not reflect immediately. Disabling cache ensures you see the latest updates without refreshing multiple times.

Steps to Disable Cache:

  • From Salesforce:
    1. Go to Session Settings in Setup.
    2. Disable the option Enable Caching and Autocomplete on Login Page.
  • From Browser:
    1. Open Developer Tools (right-click → Inspect).
    2. Go to the Network tab.
    3. Check the option Disable Cache.
  • Optional: Use a browser extension like Clear Cache to clear the cache frequently.

3. Disable Lightning Web Security

Lightning Web Security (LWS) can sometimes interfere with debugging. Disabling it temporarily in developer orgs or sandboxes can improve your debugging experience.

Steps to Disable Lightning Web Security:

  1. Navigate to Session Settings in Setup.
  2. Search for Lightning Web Security.
  3. Disable it for better debugging.
  4. Note: Do not disable this in production.

4. Perform Empty Cache and Hard Reload

After making changes to your code, perform an empty cache and hard reload to ensure the latest updates are reflected.

Steps to Perform Hard Reload:

  1. Open Developer Tools (right-click → Inspect).
  2. Right-click on the browser’s refresh button.
  3. Select Empty Cache and Hard Reload.

5. Enable Custom Formatter

Custom formatters improve the readability of debugging logs, making it easier to identify issues.

Steps to Enable Custom Formatter:

  1. Open Developer Tools (right-click → Inspect).
  2. Click on the Settings icon (gear icon).
  3. Under Preferences, scroll to Console.
  4. Enable the option Custom Formatter.

6. Add Framework Files to Ignore List

Framework-related files can clutter your debugging process with unnecessary exceptions. Adding these files to the ignore list helps you focus on your code.

Steps to Add Files to Ignore List:

  1. Open Developer Tools (right-click → Inspect).
  2. Navigate to the Ignore List under Settings.
  3. The following patterns need to be added to the ignore list:

    1. /aura_prod.*.js$

    2. /components/.*.js$

  4. Add custom exclusion rules to ignore framework files.

7. Locate Your Source Code

To debug your LWC component, you need to locate its source code in the browser.

Steps to Locate Source Code:

  1. Open Developer Tools (right-click → Inspect).
  2. Navigate to the Sources tab.
  3. Expand the Modules folder under SLDS to find your LWC components.
  4. Open the desired component’s JavaScript or HTML file.
  5. Shortcut: Use Ctrl + P to search for the component file directly.

8. Debugging Using Breakpoints

Breakpoints allow you to pause code execution at specific lines, making it easier to inspect variables and functions.

Steps to Use Breakpoints:

  1. Open the desired JavaScript file in the Sources tab.
  2. Click on the line numbers to add breakpoints.
  3. Use the following debugging controls:
    • F10: Step over to the next line.
    • F11: Step into a function.
    • Shift + F11: Step out of a function.
    • Play Button: Resume execution until the next breakpoint.

9. Programmatic Breakpoints

You can also set breakpoints programmatically using the debugger keyword. This is especially useful when debugging in developer orgs or sandboxes.

Steps to Add Programmatic Breakpoints:

  1. Add the debugger keyword in your JavaScript code where you want the execution to pause.
  2. Deploy the code and refresh the page.
  3. When the debugger keyword is encountered, the browser will pause execution automatically.

10. Pause on Uncaught Exceptions

This feature automatically pauses execution when an error occurs, even if no breakpoints are set.

Steps to Enable Pause on Uncaught Exceptions:

  1. Open Developer Tools (right-click → Inspect).
  2. Navigate to the Sources tab.
  3. Check the option Pause on Uncaught Exceptions.

11. Debugging Wire Decorators

When using @wire decorators, ensure the data is being fetched correctly.

Steps to Debug Wire Decorators:

  1. Add breakpoints in the JavaScript file where the @wire decorator is used.
  2. Check the data being returned by hovering over the variables in the debugging panel.

12. Debugging Input Validation

Input validation errors are common in LWC. Use breakpoints to inspect the validation logic and identify issues like case sensitivity or typos.


13. Debugging Lifecycle Hooks

Add breakpoints in lifecycle hooks like connectedCallback or renderedCallback to ensure they are being executed as expected.


14. Styling Debugging

Use the Elements tab in the browser’s Developer Tools to:

  • Inspect and modify styles directly.
  • Test changes like font size or color without redeploying the code.

15. Real-World Debugging Scenarios

Scenario 1: Debugging a Create Account Button

  • Issue: Clicking the button does nothing.
  • Solution:
    1. Add breakpoints in the clickHandler method.
    2. Step through the code to identify issues (e.g., variable case mismatch like valid vs. Valid).
    3. Use the Pause on Uncaught Exceptions option to catch errors automatically.

Scenario 2: Debugging a Wire Decorator

  • Issue: Data is not displayed based on user input.
  • Solution:
    1. Add breakpoints in the @wire decorator function.
    2. Check the data being returned by hovering over variables.
    3. Correct any issues in the logic (e.g., incorrect method names or case sensitivity).

Conclusion

Debugging LWC components can seem daunting at first, but with the right tools and techniques, it becomes a systematic and efficient process. By following the steps outlined in this guide, you’ll be able to identify and resolve issues quickly, ensuring your components work flawlessly.


Friday, 24 March 2023

how to design a custom object model to store complex hierarchical data structures with a large number of records while maintaining high performance and scalability

Designing a custom object model to store complex hierarchical data structures with a large number of records while maintaining high performance and scalability can be challenging. It requires careful consideration of the data model, relationships between objects, data volume, and performance optimization techniques.


One approach to address this challenge is to use a combination of master-detail and lookup relationships between objects to represent the hierarchical structure. The master-detail relationship allows you to establish a parent-child relationship between two objects, where the child object inherits some properties of the parent object and is deleted when the parent object is deleted. The lookup relationship allows you to establish a one-to-many relationship between two objects, where the child object has a reference to the parent object but is not deleted when the parent object is deleted.


Another important consideration is the data volume and performance. To handle a large number of records, you may need to use custom indexing, partitioning, or caching techniques to optimize the performance of your queries and data access. You may also need to consider asynchronous processing or batch processing to handle large data volumes without impacting the performance of your user interface.


Regarding integrating Salesforce with an external ERP system, one approach is to use a middleware platform or an integration tool that supports real-time data synchronization and provides reliable messaging and error handling. You may need to consider the data format, protocols, and security requirements of both systems and implement a data mapping and transformation layer to ensure data consistency and accuracy.


Overall, designing and implementing complex Salesforce customizations and integrations require a deep understanding of the platform's capabilities, best practices, and optimization techniques. It's essential to have a clear understanding of the business requirements and data model and to work closely with stakeholders and developers to ensure a successful outcome.

Tuesday, 15 June 2021

Apex CPU Time Limit Exceeded

 

What is a CPU timeout error?

Salesforce limits CPU usage to 10 seconds for synchronous transactions and 60 seconds for asynchronous transactions. Seeing the error “Apex CPU time limit exceeded” means your transaction is taking too long and can’t be completed. It’s also likely a signal of greater problems in your system. It’s common to see this error when you’re inserting or updating records in Salesforce, particularly when tools, integrations, and automation are putting a strain on your system.


What’s Slowing Your System Down?

Unless you have a clear idea of what’s causing your CPU timeout error, you’ll need to conduct an audit to find its source. , rather than systematically examining everything that’s going on in your system, it’s best to start where the problem is most likely to occur: on the creation of a lead, contact, or account.

Next, narrow your investigation to the types of actions that tend to create CPU timeout errors: database queries, process builders/workflow rules, and Apex code. By determining how long it’s taking your system to run each of these functions, you’ll then be able to identify which one is slowing it down.

Optimizing to Avoid CPU Timeout Errors

There are two primary situations in which a CPU timeout will occur. The first is that your processes are simple, but you’re processing too many records at once. In this case, the record count alone will force your code to hit the processing limit. To avoid this, process your manual inserts in smaller batches, schedule your automation to run only when and where you need it to, and control batch size in automated updates.

The more complicated scenario occurs when you’re processing a smaller number of records but the update is too complex for the system to handle within the CPU time limit. Below are examples of this issue, and how to avoid it.

Validation Rules

Truthfully, it’s uncommon for validation rules to cause “Apex CPU time limit exceeded” errors. But it can happen. When it does, it’s likely due to one of two reasons: either you have too many validation rules on a single object, or you have an excessive number of statements in a single validation rule. Eliminate these issues and your validation rules will run error free.

Process Builders

By far the most common reason that process builder causes CPU timeout errors is having multiple process builders on one object. It’s a best practice for process builders to have only one per Salesforce object. Alternatively, CPU timeout errors can happen when process builders are not firing on selective events, which can create a volume issue unnecessarily.

In either situation, consider migrating your automation from process builder to to an Apex trigger. Triggers can work much faster and will be less likely to cause an error.

Flows

If you’re using flows that happen after save instead of using the new before save flow feature you may run into a CPU timeout error. If you want your flows to fire before insert, you’ll need to migrate existing flows to this new model and select the “before save” option upon creation of your flow.

Apex Code

There are many situations in which Apex causes an “Apex CPU time limit exceeded” error. Here are the most common scenarios.

  • A circular update between two objects. This will cause a never-ending execution of Apex and a CPU timeout.
  • Too much processing in a before trigger. Try moving processing to an after trigger.
  • Too many nested loops. Loops more than two layers deep can sharply increase CPU time. Try using more code blocks instead of doing too much in a single set of nested loops.
  • Recursion. Having an update call the same update trigger more than once within one transaction can cause problems.
  • Querying and updating the same object many times. Instead, do one update on one object.
  • Too many triggers. Limit how many triggers you’re firing on one update.
  • Architecture issues. Multiple fields being tracked on an object like timestamps to track when different fields are updated could be all moved to a related object instead so that the related object is modified, offloading processing on an object that might already have a lot happening to it

Friday, 26 February 2021

Call a method of one class in another class : APEX : Salesforce

 You can use two approaches:

1.Use Static methods


You cannot use controller2 instance methods here

public class controller2 
{
    public static string method2(string parameter1, string parameter2) {
        // put your static code in here            
        return parameter1+parameter2;
    }
    ...
}

In a separate class file call method2()

// this is your page controller
public class controller1
{
    ...
    public void method1() {
        string returnValue = controller2.method2('Hi ','there');
    }
}

2.Create an instance of the other class

public class controller2 
{
    private int count;
    public controller2(integer c) 
    {
        count = c;
    }

    public string method2(string parameter1, string parameter2) {
        // put your static code in here            
        return parameter1+parameter2+count;
    }
    ...
}

public class controller1
{
    ...
    public void method1() 
    {
        controller2 con2 = new controller2(0);
        string returnValue = con2.method2('Hi ','there');
    }
}

If your methods are in a package with a namespace

string returnValue = mynamespace.controller2.method2();
--------------------------------------------------------------

public class ClassA {

    public list<Account> method1(){
        
        List<Account> lstacc = [SELECT Id,Name from Account];
    	return lstacc;
    }

}
////////////////////////////////////////////////////////////////
public class ClassB {
	
    ClassA ca = new ClassA();
    List<Account> acc = ca.method1();
    
    public static list<Contact> method2(List<Account> accountList){
        
        List<Contact> lstcon = [SELECT Id,LastName from Contact WHERE accountId IN: accountList];
        SYstem.debug('List of contact--->'+ lstcon);
        return lstcon;
    }
}

Thursday, 25 February 2021

Events/Tasks : Open Activities/Activity History

 There are actually four relationships for activities: 

Tasks, 

Events, 

OpenActivites

ActivityHistories. 

The two real objects are Tasks and Events

OpenActivities show open tasks and events today or in the future.

ActivityHistories shows closed tasks and events before today (in the past). 

When you want to show the history or future activity of a record, you use the two "hybrid" objects

When you want to create a real task or event, you use the two real objects (They'll automatically appear in the appropriate hybrid relationship).

Tuesday, 17 March 2015

Salesforce Contollers and Extension

In the context of visualforce, to take advantage of the built-in features of Visualforce to access your org's data, you must use a controller. All controllers are Apex classes, either standard Apex classes (ApexPages.StandardController or ApexPages.StandardSetController) or your own custom Apex class. You can also extend functionality of any of these with an Extension class.
I tend to be a bit picky with my terminology here. Controllers are controllers. Extensions are not controllers. And for me, the difference is that extensions cannot live by themselves on a page. In other words, I'm not permitted to use extensions, unless my page has a controller in the first place.
Another distinguishing feature is that a page is allowed only one controller ever. But I can add as many extensions as I need.
So let me begin (what has become a dissertation) with controllers:
Controllers are attached to your page using one of three mutually exclusive formats, standard controller, standard list/set controller, custom controller.
For a page with a single record, accessing standard data and behavior of your object you would use standard controller:
<apex:page standardController="Account"...> ... </apex:page>
If you want a page with many records, using standard list view, and list actions you could use standard list controller:
<apex:page standardController="Account" recordsetVar="accountsList"...> ... </apex:page>
If you want to use completely custom functionality and don't really need most of the standard object behaviors, custom controller is a good option, but bear in mind, any standard actions you want to use will have to be implemented in your custom class. A page with a custom controller would use the following attribute:
<apex:page controller="MyApexClass"...> ... </apex:page>
But bear in mind, you yourself can instantiate ApexPages.StandardController to use its features and functionality. I often use the pattern below to instantiate standard controller to get access to its methods:
public with sharing class MyApexClass {
  private ApexPages.StandardController ctrl;
  public Account acct {get;set;}
  public MyApexClass(){
    try{
      acct = [select Name from Account 
          where Id = : ApexPages.currentPage().getParameters().get('id')];
    } catch (QueryException e) {
      acct = new Account();
    }
      ctrl = new ApexPages.StandardController(acct);
  }
  public PageReference save(){
    //here I can put additional functionality or just leave it as-is.
    return ctrl.save();
  }
}
The above instantiates Standard Controller privately, but then surfaces a public save method that is just a pass-through of the controller's save method. The constructor does the housekeeping of creating the actual record I'm working with.
If I want to add to the functionality of any controller, I can then use an extension. Extensions work with either standard or custom controllers. Standard controller with custom extension, for me, is the most common construct I use for Visualforce that will operate inside my org. I get all the power of the standard controller, but all the flexibility of Apex. The syntax for an extension with a standard controller page would be as follows:
<apex:page standardController="account" extensions="MyExtClass"...> ... </apex:page>
The extension class is then required to implement a constructor that accepts the type of the controller. You will then typically want to get a handle to the standard controller instance that is floating around, and the sObject instance that it represents. So for a standard controller page:
public with sharing class MyExtClass {
  private ApexPages.StandardController ctrl;
  public Account acct {get;set;}
  public MyExtClass(ApexPages.StandardController controllerParam){
      ctrl = controllerParam;
      acct = (Account) ctrl.getRecord();
  }
  public PageReference customsave(){
    //here I override my standard save functionality before I return the save call.
    return ctrl.save();
  }
}
With a custom controller and extension, you can probably extrapolate from the above, but just to close the loop.
<apex:page controller="MyApexClass" extensions="MyExtClass"...> ... </apex:page>
Again, the extension class implements a constructor that accepts the type of the controller, only now it is my custom class. From there, apart from getting a local handle to your custom controller instance, there isn't a pattern, per-se, but the local handle allows you to interact directly with your custom controller, in whatever way necessary, of course. :
public with sharing class MyExtClass {
  private MyApexClass ctrl;
  public MyExtClass(MyApexClass controllerParam){
      ctrl = controllerParam;
  }
}
There are additional tricks that are very powerful, such as instantiating ApexPages.StandardSetController in your class to take advantage of that class' built-in paging, features. For more on that, there is a great video from Dreamforce 11 that shows how this can work:http://youtu.be/Js00YUpJAjs

Wednesday, 3 December 2014

Disable Trigger in Production in Salesforce

Whenever some Trigger is moved to Production there might be scenarios where we need to disable the Trigger functionality.
For that we need to create a boolean field in Custom setting followed by the sample code in the Trigger




Say Custom Setting name is 'Custom Setting Name'.
Cofig Setting Name --> ConfigSetting
Field API Name --> Disable_TriggerName__c


Boolean triggerDisabled = false;
        triggerDisabled   =  Custom_Setting_Name__c.getValues('ConfigSetting').Disable_TriggerName__c;
        if (triggerDisabled == true) {
        return;
    }

Monday, 20 October 2014

How to run the test class of Managed Package



Lets take a scenario when Managed package Class or Trigger is deployed in customer organization.
When  customer writes the new Trigger and used the managed package in the new Trigger the test for that new Trigger will show the exception

For this kind of scenarios you need to follow the below three as Managed package only runs in the three scenarios
·         On package upload (only applicable to the package author)
·         If explicitly selected to run (changing the namespace on the run dialog for Setup > Develop > Apex Test Execution, dev console, specific API calls to run them, like setting runTests in the metadata API deploy call).
·         On metadata API deployments that have the runAllTests flag set to true (see the runAllTests description).


@isTest(seealldata=true)
public class UpdateIMLocationTest {
    public static testMethod void myTest(){

 ******
 ******
 ******
 ******
PACKAGENAME__OBJECTNAME__c ** = new PACKAGENAME__OBJECTNAME__c
 ******   
}