Monday, May 29, 2023

Difference Between Wire Method And Imperative Method in LWC

In Lightning Web Components (LWC), the wire method and imperative method are two different ways of retrieving data from an Apex controller or an external data source.

The wire method is a reactive approach that retrieves data declaratively. It uses the @wire decorator to declare the properties that the component needs and the Apex method to call to get the data. When the component loads or the properties change, the wire method automatically updates the component with the new data.

The imperative method is an imperative approach that retrieves data programmatically. It uses the import statement to import the Apex method and then calls it manually using JavaScript code. This approach is useful when you need to retrieve data based on user input or component events.

Overall, the choice between the wire method and the imperative method depends on the specific use case and requirements of the component. The wire method is more suitable for simple data retrieval scenarios, while the imperative method offers more flexibility for complex data retrieval and update scenarios.

Monday, May 22, 2023

How to Automatically Refresh DataTable In LWC

To automatically refresh a Lightning web component (LWC) Datatable in Salesforce, you can use the refreshApex function from the Apex class to refresh the data and re-render the component.

The refreshApex method in LWC can only be used with the @wire decorator to retrieve data from an Apex controller.

Here's an example of how to use refreshApex to automatically refresh a Datatable every 10 seconds:

import { LightningElement, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getAccountList from '@salesforce/apex/
               AccountController.getAccountList';

export default class AccountTable extends 
                                LightningElement {
    accounts;
    error;
    refreshTable;

    @wire(getAccountList)
    wiredAccountList(result) {
        this.refreshTable = result;
        if (result.data) {
            this.accounts = result.data;
            this.error = undefined;
        } else if (result.error) {
            this.error = result.error;
            this.accounts = undefined;
        }
    }
    connectedCallback() {
        setInterval(() => {
            refreshApex(this.refreshTable);
        }, 10000);//Refresh every 10 seconds
    }
}

In this example, the connectedCallback lifecycle hook is used to set up an interval that calls the refreshApex function every 10 seconds. The refreshApex function takes the result property of the @wire adapter as an argument, which causes the adapter to fetch the latest data from the server and re-render the component.

Note that when refreshApex is called, it re-fetches the data from the server and updates the cache. If there is any change in the data, the UI will be updated with the new values. If there is no change, the UI will remain the same.

Monday, May 15, 2023

Switch Statement in Apex Salesforce

In Apex, a switch statement is a control flow statement that evaluates an expression and executes code based on the value of the expression. The switch statement is used when you have multiple conditions to check and execute different blocks of code based on those conditions.

The syntax of a switch statement in Apex is as follows:

switch on (expression) {
    when value1 {
        // code block to execute when 
expression equals value1
    }
    when value2 {
        // code block to execute when 
expression equals value2
    }
   
    when else {
        // code block to execute when 
expression does not equal any of the
        specified values
    }
}

In this syntax, expression is the expression to evaluate, and value1, value2, and so on are the values to compare the expression with. You can specify any number of when clauses, each with a different value to compare the expression with.

The when else clause is optional and specifies a default code block to execute when the expression does not equal any of the specified values.

Here is an example of a switch statement in Apex:

String dayOfWeek = 'Monday';
switch on (dayOfWeek) {
    when 'Monday' {
        System.debug('Today is Monday');
    }
    when 'Tuesday' {
        System.debug('Today is Tuesday');
    }
    when 'Wednesday' {
        System.debug('Today is Wednesday');
    }
    when 'Thursday' {
        System.debug('Today is Thursday');
    }
    when 'Friday' {
        System.debug('Today is Friday');
    }
    when else {
        System.debug('Today is a weekend day');
    }
}

In this example, the switch statement evaluates the dayOfWeek variable and executes the code block for the matching when clause. If the dayOfWeek variable does not match any of the specified values, the code block for the when else clause is executed.

Monday, May 8, 2023

Difference Between Custom Settings and Custom Metadata

Here is list of Difference Between Custom Settings and Custom Metadata Types

  1. Custom settings enable you to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user. All custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. Custom metadata are like custom setting but records in custom metadata type considered as metadata rather than data. These are typically used to define application configurations that need to be migrated from one environment to another, or packaged and installed.
  2. There are 2 types of custom setting List and Hierarchy Custom setting. There are no such types in custom metadata. Custom metadata does not support Hierarchy type of data based on user profile or specific user.
  3. You can control the visibility of custom setting by specifying it as public or protected. If custom setting is marked as protected, the subscriber organization will not be able to access the custom setting. If it is marked as public, then subscriber org can also access it. You can control the visibility of Custom Metadata Types by specifying it as public or protected. If it is marked as public type, then anyone can see it. If it is marked as protected type, in the installed managed package subscriber organization, only Apex code in that managed package can use it.
  4. Custom settings do not support relationship fields. You can create lookups between Custom Metadata objects.
  5. You can access custom setting data using instance methods and can avoid SOQL queries to database. With custom metadata types, you can issue unlimited Salesforce Object Query Language (SOQL) queries for each Apex transaction.
  6. Custom metadata type are visible in test class without “SeeAllData” annotation but custom setting data is not visible.
  7. Custom metadata records are deployable and packageable. But we can not deploy custom setting data.

Monday, May 1, 2023

Mixed DML Operation Error in Salesforce

A mixed DML Operation Error in Salesforce comes when you try to perform DML operations on setup and non-setup objects in a single transaction. DML operations on certain sObjects, sometimes referred to as setup objects(User), can’t be mixed with DML on other sObjects(Standard/Custom Objects) in the same transaction.

How do you resolve a mixed DML exception?

  • To avoid this error, we should perform DML operation on standard/custom object records in a different transaction.
  • In general all the apex classes and apex triggers execute synchronously (execute immediately).
  • If we perform DML operation on standard/custom object records asynchronously (execute in future context), we can avoid MIXED-DML-OPERATION error.
  • To execute logic asynchronously keep the logic in an apex method (in a separate apex class, not in same apex trigger) which is decorated with @future annotation.

In the below example, Account and User records are inserted in the
same transaction.
This is will throw the Mixed DML Exception.

public class MixedDMLError {
  public static void myMethod() {
      Account a = new Account(Name='XploreSFDC');
      insert a;
      Profile p=[SELECT Id FROM Profile WHERE 
Name='Standard User'];
      UserRole r = [SELECT Id FROM UserRole WHERE Name='CEO'];
      User usr = new User(alias = 'XploreSFDC'
          email='XploreSFDC@XploreSFDC.com'
          emailencodingkey='UTF-8', lastname='Max'
          languagelocalekey='en_US'
          localesidkey='en_US', profileid = p.Id
userroleid = r.Id,
          timezonesidkey='America/Los_Angeles'
          username='XploreSFDC@XploreSFDC.com');
      insert usr;
  }
}

Let us see how we can fix it

public class MixedDMLErrorFixed {
  public static void myMethod() {
      Account a = new Account(Name='XploreSFDC');
      insert a;
      FutureDemo.insertUser();
  }
}

public class FutureDemo {
  @future
  public static void insertUser() {
      Profile p=[SELECT Id FROM Profile WHERE 
Name='Standard User'];
      UserRole r = [SELECT Id FROM UserRole WHERE Name='CEO'];
      User usr = new User(alias = 'XploreSFDC'
          email='XploreSFDC@XploreSFDC.com'
          emailencodingkey='UTF-8', lastname='Max'
          languagelocalekey='en_US'
          localesidkey='en_US', profileid = p.Id
userroleid = r.Id,
          timezonesidkey='America/Los_Angeles'
          username='XploreSFDC@XploreSFDC.com');
      insert usr;
  }
}

Few Point to keep in mind:

  • Future method execute asynchronously (whenever server is free it will execute in future context).
  • We should not declare @future method in Apex Trigger.
  • @future method should be always static.
  • @future method accepts only primitive data types (Integer, String, Boolean, Date, etc…) as parameters and it won’t accept non-primitive data types (sObject,Custom Objects and standard Objects etc.. ) as parameters.
  • @future method should not contain return type. 
  • From an apex trigger we can make only make asynchronous call outs. To make call out we should include “callout = true” beside the future @annotation.
  • We cannot perform synchronous call outs from Apex Trigger.

Mostly Viewed