Friday, February 28, 2020

Difference between UserInfo.getUiTheme() and UserInfo.getUiThemeDisplayed() in Salesforce

Salesforce currently supports the below themes
Theme1—Obsolete Salesforce theme
Theme2—Salesforce Classic 2005 user interface theme
Theme3—Salesforce Classic 2010 user interface theme
Theme4d—Modern “Lightning Experience” Salesforce theme
Theme4t—Salesforce mobile app theme
Theme4u—Lightning Console theme
PortalDefault—Salesforce Customer Portal theme
Webstore—Salesforce AppExchange theme

UserInfo.getUiTheme()
This method returns the preferred theme for the current user.

UserInfo.getUiThemeDisplayed()
Use getUiThemeDisplayed to determine the theme actually displayed to the current user.

Wednesday, February 19, 2020

How to validate Email address using apex in salesforce

Sample Code

String strEmail = 'test@test.com';
Boolean bValidateEmail = Pattern.matches('[a-zA-Z0-9._-]+@[a-zA-Z]+.[a-zA-Z]{2,4}[.]{0,1}[a-zA-Z]{0,2}', strEmail.trim());
System.debug('bValidateEmail ===> '+bValidateEmail);

Output

Friday, February 14, 2020

How to access the child records from sObject using apex in Salesforce

Sometimes we run the dynamic query based on different inputs at the time we store the data in sObject or list<sObject>
from that data sometimes we have to get the child records info, to get the child records info use the
getSobject('<relationshipName>') or getSobjects('relationshipname')

Note
 custom object relationships you would use the something similar to
sObj.getSObject('Your_Custom_Object__r')

Sample Code
sObject sObj = [SELECT Id, Name, Account.Name, Account.Owner.Name FROM Contact WHERE Id = '003B000000FgA2JIAV'];

String strContactName = (String)sObj.get('Name');
String strAccName = (String)sObj.getSobject('Account').get('Name');
String strAccOwnerName = (String)sObj.getSobject('Account').getSobject('Owner').get('Name');

System.debug('Contact Name ====> '+strContactName);
System.debug('Account Name ====> '+strAccName);
System.debug('Account Owner Name ====> '+strAccOwnerName);

Output

Wednesday, February 12, 2020

How to get related files of the record using apex in salesforce

Use the below sample code to get the files related to the record using apex.
This code works for bulk records pass the list of parent ids to the method, based on parent ids it returns the files associated with the parent record.

Apex Code
public inherited sharing class ContentUtility {
 public static map<Id, list<ContentVersion>> getRelatedFiles(list<Id> lstParentIds) {

        map<Id, list<ContentVersion>> mapParentIdAndFiles = new map<Id, list<ContentVersion>>();
        map<Id, Id> mapCntIdParentId = new map<Id, Id>();

        for(ContentDocumentLink cntLink : [Select Id, ContentDocumentId, LinkedEntityId From ContentDocumentLink Where LinkedEntityId IN :lstParentIds]) {
            mapCntIdParentId.put(cntLink.ContentDocumentId, cntLink.LinkedEntityId);
        }

        if(!mapCntIdParentId.isEmpty()) {
            for(ContentVersion cv :  [SELECT Id, Title, VersionData, ContentDocumentId FROM ContentVersion WHERE ContentDocumentId IN :mapCntIdParentId.keySet() AND IsLatest = True]) {
               
                if(!mapParentIdAndFiles.containsKey(mapCntIdParentId.get(cv.ContentDocumentId))) {
                    mapParentIdAndFiles.put(mapCntIdParentId.get(cv.ContentDocumentId), new list<ContentVersion>());
                }
                
                mapParentIdAndFiles.get(mapCntIdParentId.get(cv.ContentDocumentId)).add(cv);
            }
        }
        
        return mapParentIdAndFiles;
    } 
}

Sample Code
System.debug('Related Files ===>'+ContentUtility.getRelatedFiles(new list<Id>{'a1Z54000001NplZ'}));

Monday, February 10, 2020

Difference between ( for… in ) and ( for… of ) statements in JavaScript

For… in

for… in loops over enumerable property names of an object, In each iteration, the name of the property is stored in the variable.

Ex:

var obj = {x: 5, y: 'abc', z: true};
for (var prop in obj) {
    console.log(prop + " = " + obj[prop]);
}

Output

For… of

The for...of loop is used to loop over any type of data that is iterable(arrays, maps, sets, and others).

Ex:

const digits = [0, 1, 2, 3, 4];
for (const digit of digits) {
  console.log(digit);
}

Output

Friday, February 7, 2020

Create record with default field values/pre-populate field values in Lightning Web Component(lwc)

Form Spring'20 onwards you can create the record with default field values.

This change doesn’t apply to Lightning Out, Lightning communities, or the Salesforce mobile app

Demo
HTML Code
<template>
    <lightning-card>
        <div class="slds-m-around_medium">
            <p>Create Record with pre-populate values in LWC <b></b></p>  
            <lightning-button label="Create Account" variant="brand" onclick={createRecordWithDefaultValues}></lightning-button>
        </div>
    </lightning-card>
</template>

Javascript Controller
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class CreateRecordInLWC extends NavigationMixin(LightningElement) {

    createRecordWithDefaultValues() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'new'                
            },
            state : {
                nooverride: '1',
                defaultFieldValues:"Name=Test LWC Acc,AccountNumber=123456,Rating=Hot,Phone=1234568975"
            }
        });
    }
}

Output

Thursday, February 6, 2020

How to restrict the record edit access using validation rule in salesforce

Assume once the account record is created other users can edit the record except for system administrator and record owner.

Validation Rule
AND( 
    NOT(ISNEW()),
    NOT(OR($Profile.Name == 'System Administrator', $User.Id == OwnerId))
)

above validation rule throws an error if any other user tries to edit the record.

How to download the files using URL from salesforce

Note: To download the file, require the Content Version record Ids

For Single File

Use the below URL to download the single file from the salesforce.
URL https://<YOUR_SFDC_BASE_URL>/sfc/servlet.shepherd/version/download/068XXXXXXXXXXXX

String idCntDoc = '068XXXXXXXXXXXX';
String strURL = URL.getSalesforceBaseUrl().toExternalForm() + '/sfc/servlet.shepherd/version/download/' + idCntDoc;
System.debug('URL ===> '+strURL);

For Multiple Files

URL: https://<YOUR_SFDC_BASE_URL>/sfc/servlet.shepherd/version/download/068XXXXXXXXXXXX/068XXXXXXXXXXXX
above URL downloads the files in ZIP folder

list<String> lstCntVersionIds = new list<String>{'068XXXXXXXXXXXX', '068XXXXXXXXXXXX'};

String strURL = URL.getSalesforceBaseUrl().toExternalForm() + '/sfc/servlet.shepherd/version/download/';

for(String iterator : lstCntVersionIds) {
    strURL += iterator + '/';
}

strURL = strURL.removeEnd('/');

System.debug('URL ===> '+strURL);

Wednesday, February 5, 2020

How to delete files from Content Workspace library using Apex in salesforce

Assume you have a Content Workspace library is 'Test Library' and you have few files in that library.
Now your requirement is to delete all the files from library using apex.

Test Library


Apex Code
Id idLinkedEntity = [SELECT Id FROM ContentWorkspace WHERE Name = 'Test Library' LIMIT 1].Id;

list<ContentDocument> lstCntDocsToDelete = new list<ContentDocument>();

for(ContentDocumentLink iterator : [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId =:idLinkedEntity]) {
    lstCntDocsToDelete.add(new ContentDocument(Id = iterator.ContentDocumentId));
}

if(!lstCntDocsToDelete.isEmpty() && lstCntDocsToDelete != null) {
    Database.delete(lstCntDocsToDelete, false);
    Database.emptyRecycleBin(lstCntDocsToDelete);
}

above code deletes all files from the content workspace library.



Resource
ContentWorkspace

Monday, February 3, 2020

How to check current user is guest user or not in lightning web components(lwc)

To check the current user is a guest user, import the current user’s status from @salesforce/user/isGuest

Syntax
import isGuestUser from '@salesforce/user/isGuest';
isGuestuser identifier provides the guest user information if it returns true the current is a guest user or if it returns false current user not a guest user

HTML Code
<template>
    <lightning-card>
        <div class="slds-m-around_medium">
            <p>Current User is guest or not:  <b>{isGuestUser}</b></p>  
        </div>
 </lightning-card>
</template>

Javascript Controller
import { LightningElement } from 'lwc';
import isGuest from '@salesforce/user/isGuest';

export default class currentUserInfo extends LightningElement {
    isGuestUser = isGuest;
}

Output

Sunday, February 2, 2020

Using child component methods in parent component in Lightning Web Components(lwc)

This post explains how to use the child component methods in parent component in lightning web components(lwc)

To expose a public method, decorate it with @api. Public methods are part of a component’s API. To communicate down the containment hierarchy, owner and parent components can call JavaScript methods on child components.



Ex:
ChildInLWC.html
<template>
    {upperCase}
</template>

ChildInLWC.js
import { LightningElement, api } from 'lwc';

export default class ChildInLWC extends LightningElement {
    upperCase;

    @api
    handleChangeNameToUpperCase(name) {
        this.upperCase = name.toUpperCase();
    }
}

handleChangeNameToUpperCase method is declared as public with @api decorator so another component can call this method.

ParentInLWC.html
<template>
    <lightning-card title="Call child methods in Lightning Web Components">
        <lightning-input label="Enter Name" value={nameToChange} onchange={handleOnchange} ></lightning-input>
       <c-child-in-l-w-c></c-child-in-l-w-c>
 </lightning-card>
</template>

called the child component in parent component <c-child-in-l-w-c></c-child-in-l-w-c>

ParentInLWC.js
import { LightningElement } from 'lwc';

export default class ParentInLWC extends LightningElement {
    
    nameToChange;
    
    handleOnchange(event) {
        window.console.log('value ===> '+event.target.value);
        this.template.querySelector('c-child-in-l-w-c').handleChangeNameToUpperCase(event.target.value);
    }
}
ParentInLWC.js.meta-xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="parentInLWC">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Output

Saturday, February 1, 2020

How to refer child components names in parent component in lightning web component(lwc)

When you are referring the child component name in parent component name in lightning web component some times you may face the error
LWC1010: Failed to resolve entry for the module

To resolve the error,  replace capital letters become lowercased and prefixed with a hyphen (-).

Examples:
Assume below names are the child component names

childNameInLWC
sampleDEMO
sampleDataTable
sampleDATAinLWC

refer above components like this in the parent component

<c-child-name-in-l-w-c></c-child-name-in-l-w-c>
<c-sample-d-e-m-o></c-sample-d-e-m-o>
<c-sample-data-table></c-sample-data-table>
<c-sample-d-a-t-a-in-l-w-c></c-sample-d-a-t-a-in-l-w-c>

Best practice tip
avoid more capital letters in your component name.


Resource
LWC Component folder