Friday, January 7, 2022

SOQL and its WHERE clauses Salesforce

Return the list of records: 

Account[] lstAcc = [Select Name, Phone FROM Account];

WHERE conditions:

SELECT Id, Name, Phone from Account where Name = 'SFDC Computing'

SELECT Id, Name, Phone from Account where ( Name = 'SFDC Computing' AND Employees > 25)

SELECT Id, Name, Phone from Account where (Name = 'SFDC Computing1' OR ( Name = 'SFDC Computing' AND Employees > 25))''

LIKE :

SELECT Id, Name, Phone from Account where Name LIKE 'SFDC Computing%'

ORDER BY : You can sort on most fields, including numeric and text fields. You can’t sort on fields like rich text and multi-select picklists.

SELECT Id, Name, Phone from Account Where Order by Name

SELECT Id, Name, Phone from Account Where Order by Name ASC

SELECT Id, Name, Phone from Account Where Order by Name DESC

LIMIT :

SELECT Id, Name, Phone from Account LIMIT 1

Ex: 

Single : 

SELECT Id, Name, Phone from Account Where Name Like 'Dickenson%' Order by Name LIMIT 1

Bulk:

Account[] accts = [SELECT Name,Phone FROM Account 

                   ORDER BY Name

                   LIMIT 10];

System.debug(accts.size() + ' account(s) returned.');

System.debug(accts);

Inner SOQL:

Account[] acctwithContacts = [Select Name, (Select FirstName, Lastname from Contacts) 

                         from Account 

                         where Name = 'Dickenson plc'];

Contact[] cts = acctwithContacts[0].Contacts;

System.debug('name of first contact:=====> ' +cts[0].FirstName+ ' , ' +cts[0].Lastname);

Insert List of Account with less code:

insert new Account[]{new Account(Name = 'for loop 1'), 

                                      new Account(Name = 'for loop 2'), 

                                      new Account(Name = 'for loop 3')};

Querying Record in Batches By Using SOQL For Loops :

insert new Account[]{new Account(Name = 'for loop 1'), 

                                      new Account(Name = 'for loop 2'), 

                                      new Account(Name = 'for loop 3')};

integer i=0;

integer j=0;

for(Account[] temp : [Select id, name from Account where name like 'for loop _']){

j= temp.size();

i++;    

}

system.assertEquals(3, j);  //returns 3 records

system.assertEquals(1, i);  // Since a single batch can hold up to 200 records and, only three records 

                                                    should have been returned, the loop should have executed only once

 

Friday, October 22, 2021

Queueable class implementation code

Queueable Class: 

public class ExecuteBatchQueueableJobUpdate implements Queueable {

    List<task> lstTasksToInsertAsynchronously = new List<task>();

   public boolean isTrue{set;get;}

    //Constructor

    public ExecuteBatchQueueableJobUpdate(List<task> lstTasks, boolean isInsert){

        lstTasksToInsertAsynchronously = lstTasks;

        isTrue = isInsert;

    }


    public void execute(QueueableContext context) {

        try{

            //Invoking batch job

            if(isInsert){

                BatchDMLClassForTasks.batchUpdateSObjects(lstTasksToInsertAsynchronously);

            }else{

                BatchDMLClassForTasks.batchUpdateSObjects(lstTasksToInsertAsynchronously);

            }

        }

        catch(Exception objEx){

            System.debug(LoggingLevel.ERROR,objEx.getStackTraceString() +'\n'+ objEx.getMessage());

        }

    }

}

Helper class to insert or update from Queueable:

public class BatchDMLClassForTasks {

    // insert sobjects

    public static void batchInsertSObjects(List<SObject> sObjs) {  

        if(!sObjs.isEmpty()) { 

            try {

                BatchInsertTasks batch = new BatchInsertTasks(sObjs, true);

                Database.executeBatch(batch, 150);

            } catch (Exception e) {

                System.debug('Error inserting SObjects');

            }

        } 

    }

    // update sobjects

    public static void batchUpdateSObjects(List<SObject> sObjs) {

        if(!sObjs.isEmpty()) {

            try {

                BatchInsertTasks batch = new BatchInsertTasks(sObjs, false);

                Database.executeBatch(batch, 130);

            } catch (Exception e) {

                System.debug('Error inserting SObjects');

            }

        } 

    }

}

Batch class:

public class BatchInsertTasks implements Database.Batchable<sObject> {

    private List<sObject> objectsToInsert = new List<sObject>();

    private boolean isInsertTasks;  

    public BatchInsertTasks(List<sObject> objects, boolean isInsert){

        this.objectsToInsert = objects;

        this.isInsertTasks = isInsert; 

    }

    public Iterable<sObject> start(Database.BatchableContext BC) {

        return this.objectsToInsert;

    }

    public void execute(Database.BatchableContext BC, List<task> scope){

        if(this.isInsertTasks){

            Database.insert(scope);

        }else{

            Database.update(scope);

        }

    }

    public void finish(Database.BatchableContext BC) {}

}


Reuse of Queueable class in another classes


 if(!lstTaks.isEmpty()){

     System.enqueueJob(new ExecuteBatchQueueableJob(lstTasksToInsertAsynchronously, true));

  }

Thursday, October 21, 2021

JSON Parsing and Rest Api Pagination

 public integer multifetchapi(integer totalcount){

        integer defCount = 50;

        integer pageNumber = 0;

        Test__c obj= [SELECT Access_Token__c,Refresh_Token__c from Test__c  where Name = 'testName'];

        string strAuth=obj.Access_Token__c;

        Http http= new Http();

        HttpRequest req= new HttpRequest();

        req.setMethod('GET'); 

        req.setEndpoint('https://test.com/companies');

        req.setHeader('Authorization', 'Bearer '+strAuth);

        HttpResponse strResp=http.send(req);

        system.debug('--strResp--->'+strResp.getBody());

         if(strResp.getStatusCode()==200){

            system.debug('--strResp1--->'+strResp.getBody());

             Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(strResp.getBody());             

             Map<String, Object> statusResults = (Map<String, Object>)(results.get('filtered_count_map'));

             system.debug('statusResults==>'+statusResults);

             totalcount = integer.valueOf(statusResults.get('all'));

             if(totalcount > defCount){

                 pageNumber = defCount/totalcount; 

             }

             system.debug('pageNumber==>'+pageNumber);

             

         }

        return pageNumber;

    }

for(integer i=0; i<filterCount; i++){

            string strEndPoint=zic.Endpoint_Url__c+'?page='+i;//+'?filters=updated:gt:'+updated

}


Thursday, September 30, 2021

Queueable Apex

 First Batch:

global class BatchCalledThroughQueueable implements Database.Batchable<sObject>, Database.Stateful, Database.AllowsCallouts {

    global Database.QueryLocator start(Database.BatchableContext bc) {

        return Database.getQueryLocator(query);

    }

    global void execute(Database.BatchableContext bc, List<Lead> records){

    }

    global void finish(Database.BatchableContext bc){

    }

}

Second Queueable Class:

public class ExecuteBatchQueueableJob implements Queueable {

    public void execute(QueueableContext context) {

        try{

            BatchCalledThroughQueueable b = new BatchCalledThroughQueueable();

            Database.executeBatch(b, 200);

        }catch(Exception e){

            System.debug('@@@ Error Message : '+e.getMessage());

        }

    }

}

Third Batch:

global class BatchUpdate implements Database.Batchable<sObject>, Database.StatefulDatabase.AllowsCallouts {

        global Database.QueryLocator start(Database.BatchableContext bc) {

            Note: Calling Queueable job for calling the next batchfor chaining.

                System.enqueueJob(new ExecuteBatchQueueableJob());

            return Database.getQueryLocator(query);

        }

    global void execute(Database.BatchableContext bc, List<Contact> records){

    }

    global void finish(Database.BatchableContext bc){

    }

}

Wednesday, September 15, 2021

Instance Refresh and find hardcode instance like : NA65, CA38 in entire org

 


To find hardcode instances like NA65, CA38 in the entire org. 

Need to check below in components and follow reference links :

1. Static Resources

2. Custom Button or Link (Javascript)

3. Email Template 

4. Remote site settings

5. Visualforce pages

6. Custom lables





Reference links:

Lightning Experience Configuration Converter: https://lightning-configuration.salesforce.com/

https://www.infallibletechie.com/2018/09/things-to-consider-during-salesforce.html

Wednesday, September 8, 2021

LWC NavigationMixin - Redirect to parent record and LWC Headless action redirection

1. Reference link for LWC Headless action:

NOTE: This headless action is supported only on the standard record page. - Not worked for community's ref link:  

https://help.salesforce.com/s/articleView?language=en_US&type=5&release=232&id=release-notes.rn_lwc_quick_actions.htm


2. Navigate to LWC or Aura component with RecordId

handleAction(event) {
  var RecIdJSON.stringify(event.detail.row.Id);
    this[NavigationMixin.Navigate]({
        "type": "standard__component",
        "attributes": {
            "componentName": "c__TestForm" //if LWC component : c___test_form
        },
        state: {
            c__recordId: JSON.parse(RecId)
        }
    });
}
(OR)
    renderedCallback() {
        this.sfdcBaseURL = window.location.origin;
    }
 
    handleAction(event) {
var RecIdJSON.stringify(event.detail.row.Id);
       this[NavigationMixin.Navigate]({
                 "type": 'standard__webPage',
                 "attributes": {
                   "url": this.sfdcBaseURL+'/lightning/cmp/c__TestForm?c__recordId='+JSON.parse(RecId)
                 }
             });
    }


3. Sample Redirection to parent record:

XML:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightningCommunity__Page</target>
        <target>lightningCommunity__Default</target>
        <target>lightning__RecordAction</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordAction">
            <actionType>ScreenAction</actionType>
        </targetConfig>
        <targetConfig targets="lightning__RecordPage">
            <objects>
                <object>Contact</object>
            </objects>
        </targetConfig>
        <targetConfig targets="lightningCommunity__Default">
            <property name="recordId" type="String" label="Record ID" 
description="Should be set to {!recordId}" default="{!recordId}"/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

 Template:

<template>
    <div class="slds-clearfix">
        <div class="slds-float_right">
            <lightning-button label="Return to Roadmap" 
onclick={navigateToViewAccountPage}></lightning-button>
        </div>
    </div>
</template>


JS

  import { LightningElementapiwire } from 'lwc';
  import { getRecord } from 'lightning/uiRecordApi';
  import { NavigationMixin } from 'lightning/navigation';
  
  const FIELDS = ['Contact.Account.Name',
'Contact.Account.Id']; 

  export default class ReturnToRoadmapLWC extends NavigationMixin (LightningElement){
      @api recordId;  

      connectedCallback(){
        console.log('recordid========='+this.recordId);
      }

      //Wire the output of the out of the box method getRecord to the Contact object
      @wire(getRecord, { recordId: '$recordId'fields: FIELDS })
      Contact;
  
      //Navigate to Account record from Contact
      navigateToViewAccountPage(event) {
        var AccountName this.Contact.data.fields.Account.value.fields.Name.value;
        var AccountId this.Contact.data.fields.Account.value.fields.Id.value;            
          console.log('Contact Account name ========='AccountName);
          console.log('Contact Account ID ========='AccountId);
        this[NavigationMixin.Navigate]({
            type: 'standard__webPage',
            attributes: {
              url: '/'+AccountId
                //url: '/hello/s/testurl/'+AccountId+'/'+AccountName
            }
        });
      }
  }

Thursday, July 29, 2021

Date.ValueOf not accepting null

 String str = null;

 Date d = Date.valueOf(str);

I am getting the following error when running the above snippet in Anon Apex.


Line: 2, Column: 1


System.NullPointerException: Argument cannot be null.


Resolution:  Using Ternary Operator we can fix the null check

Date d = String.isBlank(str)  ?  null  : Date.valueOf(str);

CSS Styling

Styling: 1. Inline Styling: < div style = "font-size: 2rem;font-weight: 400;" > Good Evening </ div > 2. Usi...