Monday, March 30, 2020

Tree Grid in Lightning Web Components(lwc)

HTML Code
<template>
    <lightning-card title="Tree Grid in Lightning Web Components">
        <lightning-tree-grid columns={gridColumns} data={gridData} key-field="Id">
        </lightning-tree-grid>
    </lightning-card>
</template>

Javascript Code
import {
    LightningElement,
    wire
} from 'lwc';
import fetchAccs from '@salesforce/apex/GenericController.returnAccsWithCons';

export default class TreeGridInLWC extends LightningElement {
    gridData;

    gridColumns = [{
            type: 'text',
            fieldName: 'Name',
            label: 'Name'
        },
        {
            type: 'text',
            fieldName: 'Industry',
            label: 'Industry'
        },
        {
            type: 'text',
            fieldName: 'FirstName',
            label: 'FirstName'
        },
        {
            type: 'text',
            fieldName: 'LastName',
            label: 'LastName'

        }
    ];


    @wire(fetchAccs)
    accsWithCons({
        error,
        data
    }) {
        if (data) {
            let parseData = JSON.parse(JSON.stringify(data));

            for (let i = 0; i < parseData.length; i++) {
                parseData[i]._children = parseData[i]['Contacts'];
                delete parseData[i]['Contacts'];
            }

            this.gridData = parseData;
        } else if (error) {
            console.log('error ====> ' + JSON.stringify(error));
        }
    }
}
Apex Class
public inherited sharing class GenericController {
    
    @AuraEnabled(Cacheable=true)
    public static list<Account> returnAccsWithCons(){
        return [SELECT Id, Name, Industry, Type, (SELECT Id, FirstName, LastName FROM Contacts) FROM Account];
    }
}

Output

Wednesday, March 25, 2020

Progress ring/circular in lightning web components(lwc)

HTML Code
<template>
    <lightning-card title="Progress ring in Lightning Web Component"><br/>
        <div>
            <lightning-progress-ring variant="base-autocomplete" value={progress} size="large" class="slds-align_absolute-center"> </lightning-progress-ring>
        </div>
        <div class="slds-text-align--center slds-text-title" style="color:forestgreen;">
            {processStatus}
        </div>
    </lightning-card>
</template>

JS Code
import { LightningElement, track } from 'lwc';

export default class ProgressBarDemoInLWC extends LightningElement {
    progress = 0;
    processStatus = 'In Progress';
    connectedCallback() {
        // eslint-disable-next-line @lwc/lwc/no-async-operation
        this._interval = setInterval(() => {
            this.progress = this.progress + 5;
            this.processStatus = 'Processing => ' + this.progress +'/100';
            if(this.progress === 100) {
                clearInterval(this._interval);
                this.processStatus = 'Completed';
            }
        }, 300);

    }
}

Output

Monday, March 23, 2020

System.CalloutException: Read timed out error in Salesforce

When you are sending the request to other systems sometimes you may face the fatal error like
System.CalloutException: Read timed out error

To resolve the issue increase the timeout limit,
the minimum timeout limit is  1 millisecond
the maximum timeout limit is 120 seconds (2minutes).

The request.setTimeout method accepts the parameter is an integer in milliseconds so pass the value in milliseconds

Ex: 20 sec * 1000  ms / sec = 20,000 ms

Sample Code

HttpRequest httpRequest = new HttpRequest();    
httpRequest.setEndpoint('https://www.salesforcecodecrack.com/');
httpRequest.setTimeout(120000);
httpRequest.setMethod('GET');   
httpRequest.setHeader('Authorization', 'OAuth ' + getSessionId());        
httpRequest.setHeader('Authorization', 'Bearer ' + getSessionId()); 
httpRequest.setHeader('Content-Type', 'application/json');
httpRequest.setHeader('Accept', 'application/json');

Http http = new Http();
HTTPResponse res = http.send(httpRequest);
String strResponse = res.getBody();

Sunday, March 22, 2020

How to Open files in separate tab/new tab in visual studio code

By default, in Visual Studio Code, files open in the same tab instead of a separate tab.

To force to open separate tab/new tab in visual studio code then Disable the Preview Mode.

File -> Preferences -> Settings

In Settings -> Type “preview” in the search text field and uncheck the Enable Preview as highlighted.

That's it, now when you open any file in visual studio code it opens the file in a separate window/tab.

How to set default value in Combo box in Lightning Web Components(lwc)

To set the default value in the Combo box assign the value in js code directly.

Ex:

HTML Code
<template>
    <lightning-combobox
            name="progress"
            label="Status"
            value={value}
            placeholder="Select Progress"
            options={options}
            onchange={handleChange} ></lightning-combobox>

    <p>Selected value is: {value}</p>
</template>

JS Code
import { LightningElement, track } from 'lwc';

export default class ComboboxBasic extends LightningElement {
    value = 'inProgress';

    get options() {
        return [
            { label: 'New', value: 'new' },
            { label: 'In Progress', value: 'inProgress' },
            { label: 'Finished', value: 'finished' },
        ];
    }

    handleChange(event) {
        this.value = event.detail.value;
    }
}

Output

Tuesday, March 17, 2020

how to clone a record using apex in salesforce

Salesforce sObject class has a method called clone() which creates a copy of the sObject record. This method has four Boolean type optional parameters.
clone(Boolean preserveId, Boolean isDeepClone, Boolean preserveReadonlyTimestamps, Boolean preserveAutonumber)

 preserveId:  Determines whether the ID of the original object is kept or cleared in the duplicate. If set to true, the ID is copied to the duplicate. The default is false, that is, the ID is cleared.

 isDeepClone:  Determines whether the method creates a full copy of the sObject field or just a reference:
* If set to true, the method creates a full copy of the sObject. All fields on the sObject are duplicated in memory, including relationship fields. Consequently, if you make changes to a field on the cloned sObject, the original sObject is not affected.
* If set to false, the method performs a shallow copy of the sObject fields. All copied relationship fields reference the original sObjects. Consequently, if you make changes to a relationship field on the cloned sObject, the corresponding field on the original sObject is also affected, and vice-versa. The default is false.

preserveReadonlyTimestamps: Determines whether the read-only timestamp fields are preserved or cleared in the duplicate. If set to true, the read-only fields CreatedById, CreatedDate, LastModifiedById, and LastModifiedDate are copied to the duplicate. The default is false, that is, the values are cleared.

preserveAutonumber: Determines whether auto-number fields of the original object are preserved or cleared in the duplicate. If set to true, auto number fields are copied to the cloned object. The default is false, that is, auto number fields are cleared.

Example
Account objAcc = new Account(Name = 'Test Acc', Industry = 'Banking', Phone = '1234567890');
insert objAcc;    
 
//Clone the record
Account accClone = objAcc.clone(false, false, false, false);
insert accClone;


Below are the few of the cloning methods:

isClone() - Returns true if an entity is cloned from something, even if the entity hasn’t been saved.

Example
trigger clonetest on sObject (before insert) {
    for (sObject obj : Trigger.new) {
        if (obj.isClone()) {
            System.debug( 'isClone: ====>  '+ obj.isClone());
        }
    }
}


getCloneSourceId() - Method gives the salesforce id of the source record from where the new record is cloned.

Example
 trigger clonetest on sObject (before insert) {
    for (sObject obj : Trigger.new) {
        if (obj.isClone()) {
            System.debug( ' isClone: ====>  '+ obj.getCloneSourceId());
        }
    }
}

NOTE: getCloneSourceId() Always return null in salesforce lightning. This is already reported as BUG in salesforce.


Monday, March 9, 2020

Convert Lead using Apex in Salesforce

Sample Code
Lead objLead = new Lead();
objLead.LastName = 'Test Lead';
objLead.LeadSource = 'Website Lead';
objLead.Method_of_Contact__c = 'Phone';
objLead.Status = 'New Lead';
objLead.Phone = '1234567890';
insert objLead;

Database.LeadConvert leadCnvrt = new Database.LeadConvert();
leadCnvrt.setLeadId(objLead.id);

LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted = true LIMIT 1];
leadCnvrt.setConvertedStatus(convertStatus.MasterLabel);

Database.LeadConvertResult leadCnvrtRes = Database.convertLead(leadCnvrt);
System.assert(leadCnvrtRes.isSuccess());

if(leadCnvrtRes.isSuccess()) {
 System.debug('Converted Opp Id ====> '+leadCnvrtRes.getOpportunityId();
 System.debug('Converted Acc Id ====> '+leadCnvrtRes.getAccountId();
}        

Resource
LeadConvertResult
LeadConvert Class

Check Lead Status picklist values marked as converted or not In Apex

In Order to retrieve the Lead Status Picklist Values we have Standard Salesforce object "LeadStatus".

LeadStatus object represents the status of a Lead, such as Open, Qualified or Converted.

This object represents a value in the lead status picklist (see Lead Status Picklist). The lead status picklist provides additional information about the status of a Lead, such as whether a given status value represents a converted Lead. Query this object to retrieve the set of values in the lead status picklist, and then use that information while processing Lead objects to determine more information about a given lead.

SOQL
SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted = true

Result

Resource
LeadStatus

Thursday, March 5, 2020

How to find last date of the month in formula in salesforce

In this formula, I am using today's date you can replace your date.

Sample Formula
IF(
  MONTH(TODAY()) = 12,
  DATE( YEAR( TODAY()), 12, 31 ),
  DATE( YEAR( TODAY() ), MONTH ( TODAY() ) + 1, 1 ) - 1
)

Output

Wednesday, March 4, 2020

How to create custom URL button or link in Lightning experience with default field values in salesforce

From Spring'20 onwards you can create the custom URL button with default field values.

you can define the default values while launches the custom button or custom link or custom code to create a new record with prepopulated field values.

Sample Code
/lightning/o/Account/new?defaultFieldValues=
    Name={!URLENCODE(Account.Name)},
    OwnerId={!Account.OwnerId},
    AccountNumber={!Account.AccountNumber},
    NumberOfEmployees=35000,
    CustomCheckbox__c={!IF(Account.SomeCheckbox__c, true, false)}

Note: The URLENCODE function works only when creating custom buttons and links. You can’t use it for custom fields.

Demo
Create a new opportunity from the account detail page with populate account values and some of the prepopulated filled values in new opportunity creation form.

Step:1



Step: 2
add the button to the account page layout and click on the new opportunity button.



Output


Note:
  •  The URLENCODE function works only when creating custom buttons and links. You can’t use it for custom fields.
  • URL Hack working only in New Record and not in the Edit forms

Demo Sample:
/lightning/o/Opportunity/new?defaultFieldValues=
    Name={!URLENCODE(Account.Name)},
    OwnerId={!Account.OwnerId},
    Days_To_Close__c=30,
    TotalOpportunityQuantity=2,
    NextStep=Call%20to%20customer,
    Type=New%20Customer



Refereence
https://releasenotes.docs.salesforce.com/en-us/spring20/release-notes/rn_general_lex_navigate_to_record_dfv.htm