Play Games

Search This Blog

Thursday, February 17, 2022

How to display circular or square photo of a user in lightning - Salesforce Globe For You

Solution: Use lightning-avatar component to display an image and set the variant attribute to 'circle' to display circular image or 'square' to display a rectangular image.

Example:

public class DisplayUserPhotoController {

    @AuraEnabled

    public static List<User> getUsers() {

        List<User> lstUser = new List<User>();

        lstUser = [Select id,name,SmallPhotoUrl,FullPhotoUrl from User Limit 5];

        return lstUser;

    }

}

displayUserPhotoInLWC.html

<template>

    <lightning-card title="List Of Users">

        <template for:each={lstUser} for:item="objUser">

            <div key={objUser.Id} class="slds-p-bottom_xx-small">

                <lightning-avatar src={objUser.SmallPhotoUrl} variant="circle" alternative-text={objUser.Name} key={objUser.Id}>

                </lightning-avatar> {objUser.Name}

            </div>

        </template>

    </lightning-card>

</template>

displayUserPhotoInLWC.js

import { LightningElement,api } from 'lwc';

import getUsers from '@salesforce/apex/DisplayUserPhotoController.getUsers';

export default class DisplayUserPhotoInLWC extends LightningElement {

    @api lstUser = [];

    connectedCallback() {

        getUsers()

        .then(result => {

            if(result){

                this.lstUser = result;

            }

        })

        .catch(error => {

            this.error = error;

        });

    }

}

displayUserPhotoInLWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>51.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__RecordPage</target>

        <target>lightning__AppPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>

Output:



How to get the url of the salesforce user photo in Salesforce - Salesforce Globe For You

How to get the url of the salesforce user photo in Salesforce

Solution: query the SmallPhotoUrl and FullPhotoUrl fields from user object for that particular user.

Example query: select id,name,SmallPhotoUrl,FullPhotoUrl from user where id='00590000001O70CAAS'

Here id is the user id.

SmallPhotoUurl will give the URL for a thumbnail of the user's profile photo

FullPhotoUrl will give the URL for the user's profile photo

Output:



How to upload user's photo or customize user profile photo in Salesforce - Salesforce Globe For You

How to upload user's photo or customize user profile photo in Salesforce - Salesforce Globe For You

Solution: 

For logged in User:

Click on the icon on the top right side of the salesforce screen which is shown below


Again click on the same icon.


It will be redirected to the following screen


click the camera icon and then on Update photo


Upload the photo here and save.it will be set for that user.

For other user: Go to setup --> Users --> users --> click on full name of selected user -->on the top right you can find the user profile link as shown below.


click on User profile link and from here its same.

How to generate random numbers with in the range in Salesforce - Salesforce Globe For You

How to generate random numbers with in the range in Salesforce - Salesforce Globe For You

Solution: For example the random numbers with in the range 995-1000 needs to be generated.

Apex Class:RandomNumberGenerator

Public class RandomNumberGenerator {

    public static List<Integer> generateRandomNumbers(Integer Min,Integer Max) {

        List<Integer> lstRandomNumber = new List<Integer>();

        Integer totalNumber = Max-Min;

        Integer len = string.valueOf(Max).length();

        Integer maxRange = 1;

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

            maxRange = maxRange *10;

        }

        while(lstRandomNumber.size() <= totalNumber){

            Integer randomNumber;

            Boolean doWhileCondition = true;

            do {

                randomNumber = (math.random() * maxRange).intValue();

                if(randomNumber >= Min && randomNumber <= Max && !lstRandomNumber.contains(randomNumber)) {

                    lstRandomNumber.add(randomNumber);

                    doWhileCondition = false;

                }

            } while (doWhileCondition);

             }

        return lstRandomNumber;

    }

}

Output: run the following code in Developer console

List<Integer> lstRandomNumber = new List<Integer>();

lstRandomNumber = RandomNumberGenerator.generateRandomNumbers(995,1000);

system.debug('Random Numbers: '+lstRandomNumber);



Tuesday, February 15, 2022

How to create custom metadata type records from apex - Salesforce Globe For You

Solution:

Step1 : create a class which implements DeployCallback interface. HandleResult() needs to be implemented.

public class CreateMetadataController implements Metadata.DeployCallback {

    public void handleResult(Metadata.DeployResult result, Metadata.DeployCallbackContext callbackContext) {

        if(result.status == Metadata.DeployStatus.Succeeded) {

            system.debug('Custom metadata record creation is successful: '+result);

        } else {

            system.debug('Custom metadata record creation failed: '+result);

        }

    }

}

Step 2: create any method and write the logic to deploy inside it.

public void createCustomMetadataRecord() {

//2.1 create the custom metadata record to be inserted

//In this example Country_Code__mdt metadata record will be inserted

Metadata.CustomMetadata objCustomMetadata =  new Metadata.CustomMetadata();

objCustomMetadata.fullName = 'Country_Code__mdt.India';// custom metadata object api name.name

objCustomMetadata.label = 'India';

//2.2 add custom fields using CustomMetadataValue

Metadata.CustomMetadataValue objCustomField1 = new Metadata.CustomMetadataValue();

objCustomField1.field = 'Code__c';

objCustomField1.value = 'IND';

objCustomMetadata.values.add(objCustomField1);

//2.3 add custom metadata to the DeployContainer

Metadata.DeployContainer objContainer = new Metadata.DeployContainer();

objContainer.addMetadata(objCustomMetadata);

//2.4 deploy the metadata using Metadata.Operations.enqueueDeployment()

Metadata.Operations.enqueueDeployment(objContainer,new CreateMetadataController);

}

overall apex class

public class CreateMetadataController implements Metadata.DeployCallback {

    public void handleResult(Metadata.DeployResult result, Metadata.DeployCallbackContext callbackContext) {

        if(result.status == Metadata.DeployStatus.Succeeded) {

            system.debug('Custom metadata record creation is successful: '+result);

        } else {

            system.debug('Custom metadata record creation failed: '+result);

        }

    }

    public static void createCustomMetadataRecord() {

        Metadata.CustomMetadata objCustomMetadata =  new Metadata.CustomMetadata();

        objCustomMetadata.fullName = 'Country_Code__mdt.India';

        objCustomMetadata.label = 'India';

        

        Metadata.CustomMetadataValue objCustomField1 = new Metadata.CustomMetadataValue();

        objCustomField1.field = 'Code__c';

        objCustomField1.value = 'IND';

        objCustomMetadata.values.add(objCustomField1);

        

        Metadata.DeployContainer objContainer = new Metadata.DeployContainer();

        objContainer.addMetadata(objCustomMetadata);

                Metadata.Operations.enqueueDeployment(objContainer,new CreateMetadataController());

    }

}

Step 3: call the above method from developer console

CreateMetadataController.createCustomMetadataRecord();

Output:





Friday, February 11, 2022

System.CalloutException: Unauthorized endpoint, please check Setup->Security->Remote site settings - Salesforce Globe For You

System.CalloutException: Unauthorized endpoint, please check Setup->Security->Remote site settings - Salesforce Globe For You

Problem: This error generally occurs when the callout is made to any external system endpoint 

without adding the base URL of endpoint in the remote site settings of Salesforce

Solution: Go to Setup --> Security --> Remote Site Settings 


click the 'New Remote Site' button and add the endpoint url in Remote Site Url.


Give any name ,keep active checkbox as true and save the record.

That's it. Now execute the same code again and it works.

Thursday, February 10, 2022

How to create a chatter group in Salesforce - Salesforce Globe For You

Solution: Users can communicate and share using chatter groups

Step 1: Login to Salesforce --> Go to App Launcher --> Search with 'Groups' in search bar 

as shown in the image below


On clicking the groups link,the groups tab will get opened as shown in the image below


Step 2: Click on 'New' button to create new Group.


Fill all the mandatory fields --> Save & Next --> Next --> Select list of group users --> Done.

The chatter group gets created.



Wednesday, February 9, 2022

How to send custom notifications to a user in Salesforce - Salesforce Globe For You

How to send custom notifications to a user in Salesforce - Salesforce Globe For You

Solution: Use the Messaging.CustomNotification class to create, configure, and send custom notifications directly from Apex.

Step 1: create custom notification type by navigating to setup --> Notification Builder --> Custom  Notifications --> New as shown in the image below.



Step 2: Use the sample apex code to send the notification

public class CustomNotificationController {

    public static void sendNotification() {

        List<CustomNotificationType> lstNotificationType = new List<CustomNotificationType>();

        lstNotificationType = [SELECT Id, DeveloperName FROM CustomNotificationType 

                                WHERE DeveloperName='Test_Custom_Notification'];

        Messaging.CustomNotification objNotification = new Messaging.CustomNotification();

        objNotification.setNotificationTypeId(lstNotificationType[0].Id);

        objNotification.setTitle('Testing Custom Notification');

        objNotification.setBody('This is a test Sample Notification');

        objNotification.setTargetId(userInfo.getUserId());

        Set<String> setAddress = new Set<String>();

        setAddress.add(userInfo.getUserId());

        try {

            objNotification.send(setAddress);

        }

        catch (Exception e) {

            System.debug('Exception: ' + e.getMessage());

        }

    }

}

You can call this code from apex trigger or from developer console anywhere.

In this example,its called from developer console

CustomNotificationController.sendNotification();

Output:


Note: This custom notification is available only in Salesforce Lightning experience.

Tuesday, February 8, 2022

Query all fields(FIELDS()) in SOQL Salesforce - Salesforce Globe For You

Query all fields(FIELDS()) in SOQL Salesforce - Salesforce Globe For You

Solution: FIELDS() can be added in SOQL query to add all/only standard/only custom fields.

FIELDS(ALL) — to select all the fields of an object.

FIELDS(CUSTOM) — to select all the custom fields of an object.

FIELDS(STANDARD) — to select all the standard fields of an object.

Example: Open query editor of developer console and run the query

SELECT FIELDS(CUSTOM) FROM CASE Limit 200

Output:

Note: There are some limitations as of now whether the FIELDS() functions are supported for Bounded and unBounded queries.

Go through the table given in the link below for more details

https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_fields.htm#limiting_result_rows

Saturday, February 5, 2022

Search functionality in Lightning Web Component - Salesforce Globe For You




Solution: In this example,you can search the leads that are existing in the system.

Apex Class: LeadController

public class LeadController {

    @AuraEnabled

    public static List<Lead> getLeads(String leadName) {

        system.debug('Lead:'+leadName);

        leadName = '%' + leadName + '%';

        List<Lead> lstLead = new List<Lead>();

        lstLead = [Select id,name,leadSource from Lead WHERE Name LIKE :leadName order by Createddate];

        system.debug('lstLead:'+lstLead);

        return lstLead;

    }

}

searchFunctionalityInLWC.html

<template>

    <lightning-card title="Search Functionality in LWC" icon-name="standard:Lead">

        <lightning-layout multiple-rows="true" vertical-align="end">

            <lightning-layout-item size="12" small-device-size="10" medium-device-size="8" large-device-size="6" padding="around-small">

                    <div class="slds-form-element">

                            <div class="slds-form-element__control">

                                    <lightning-input type="search" 

                                                     label="" value={searchString} placeholder="Search Lead"

                                                     onkeyup={handleSearch} ></lightning-input>

                            </div>

                        </div> 

            </lightning-layout-item>

            

            </lightning-layout><br/>


        <div if:true={lstLead}>

            <table class="slds-table slds-table_bordered slds-border_left slds-border_right">

                <thead>

                  <tr class="slds-line-height_reset">

                    <th class="" scope="col">

                      <div class="slds-truncate" title="Name">Id</div>

                    </th>

                    <th class="" scope="col">

                      <div class="slds-truncate" title="Some Custom Column">Name</div>

                    </th>

                  </tr>

                </thead>

                <tbody>

                    <template for:each={lstLead} for:item="objLead" for:index="index">  

                        <tr key={objLead.Id}>

                            <td>

                                <div class="slds-p-left_small" key={objLead.Id} data-leadid = {objLead.Id} onclick={navigateToLead}>  

                            {objLead.Id} </div> 

                            </td>

                            <td><div class="slds-p-left_small" key={objLead.Id} data-leadid = {objLead.Id} onclick={navigateToLead}>  

                                {objLead.Name}  </div>

                            </td>

                        </tr>

                    </template>

                </tbody>

            </table>

              

        </div>

    </lightning-card>

</template>

searchFunctionalityInLWC.js

import { LightningElement,api } from 'lwc';

import { NavigationMixin } from 'lightning/navigation';

import serachLeadRecords from '@salesforce/apex/LeadController.getLeads';

export default class SearchFunctionalityInLWC extends NavigationMixin(LightningElement) {

    @api searchString='';

    @api errorMsg ='';

    @api lstLead =[];

    handleSearch(event) {

        this.searchString = event.target.value;

        console.log('search:',event.target.value);

        

        serachLeadRecords({leadName : this.searchString})

        .then(result => {

            console.log('Result:',result);

            this.lstLead = result;

        })

        .catch(error => {

            this.lstLead = undefined;

        }) 

    }

    navigateToLead(event) {

        const selectedRecordId = event.target.dataset.leadid;

        console.log('Event',selectedRecordId);

        this[NavigationMixin.Navigate]({

            type: 'standard__recordPage',

            attributes: {

                recordId: selectedRecordId,

                actionName: 'view',

            },

        });

    }

}

searchFunctionalityInLWC.js-meta.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>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>

Output:



Friday, February 4, 2022

List of important topics to prepare for Salesforce Interviews - Salesforce Globe For You

List of important topics to prepare for Salesforce Interviews - Salesforce Globe For You

1)Sharing Settings(org wide defaults,sharing rules)

2) Different ways of sharing a salesforce record.

3) Apex Sharing

4) Batch Apex

5) Bulk Triggers

6) Future methods

7) Custom metadata types

8) Custom Settings

9) Named Credentials

10) With sharing/without sharing/inherited keywords

11) Change Data Capture.

12) Platform Events

13) Rest and Soap Integration

14) Connected App

15) Bulk data loads

16) Handling large data volumes(Data Skews).

17)Apex Enterprise Design Patterns

18)Stub

19)CI/CD process

20)Streaming Api

21)Flows

22) Dynamic forms

23)Design Patterns

24) Best practices to follow in Apex,trigger and in LWC.

25)communication between parent and child components(Passing parameters)

26)Shadow DOM

27)Designing Reusuable Lightning components.

The list goes on...

Understanding the topic clearly is very important to clear any interview.

So concentrate on clarity of the topic that you are preparing.

All the best.

How to retrieve the custom meta data records in apex Salesforce - Salesforce Globe For You

How to retrieve the custom meta data records in apex Salesforce - Salesforce Globe For You

Solution: Use the getAll() to retrieve custom medata records in Apex without using SOQL query.

Example:

Assume Country_Code__mdt is created with custom field code__c as shown in image below


Run the following piece of code in Developer Console

Map<String,Country_Code__mdt> mapCountryCodes = new Map<String,Country_Code__mdt>();

mapCountryCodes = Country_Code__mdt.getAll();

System.debug('mapCountryCodes: '+mapCountryCodes);

Output:



Thursday, February 3, 2022

Find the number of days between two given dates in Salesforce - Salesforce Globe For You

Solution: Use daysBetween() of Date class.

Syntax: startDate.daysBetween(enddate);

Example:

Date startDate = Date.valueOf('2022-01-1');

Date endDate =  system.Today();

Integer numberOfDays = startDate.daysBetween(endDate);

System.debug('Number of Days: '+numberOfDays);

Output:



Wednesday, February 2, 2022

How to filter a list based on some conditions in javascript file of Lightning web component - Salesforce Globe For You

How to filter a list based on some conditions in javascript file of Lightning web component - Salesforce Globe For You

Problem: For example I have a variable which holds list of Lead records fetched from backend apex method.Now I need to create a new variable 

which will hold only Leads whose LeadSource is Web.

Solution: Repeat the existing list using for each loop and then add each element to new list only if that specific condition met.

Example:

Apex Class: LeadController

public class LeadController {

    @AuraEnabled(cacheable=true)

    public static List<Lead> getLeads() {

        List<Lead> lstLead = new List<Lead>();

        lstLead = [Select id,name,leadSource from Lead order by Createddate Limit 3];

        return lstLead;

    }

}

filterRecordsInLWC.html:

<template>  

    <lightning-card title="Iteration of Lead Records In LWC">  

      <div class="slds-p-around_small">  

        <template for:each={lstLead} for:item="objLead" for:index="index">  

          <div class="slds-p-left_small" key={objLead.Id}>  

            Name: {objLead.Name}  Lead Source :{objLead.LeadSource}  

          </div>  

        </template>  

      </div>  

    </lightning-card><br/>

    <lightning-card title="Filtering of Lead Records In LWC">  

        <div class="slds-p-around_small">  

          <template for:each={lstFilteredLead} for:item="objLead" for:index="index">  

            <div class="slds-p-left_small" key={objLead.Id}>  

              Name: {objLead.Name}  Lead Source: {objLead.LeadSource} 

            </div>   

          </template>  

        </div>  

    </lightning-card>  

</template>

filterRecordsInLWC.js:

import { LightningElement, wire ,track} from 'lwc';

import getLeads from '@salesforce/apex/LeadController.getLeads';

export default class FilterRecordsInLWC extends LightningElement {

    @track lstLead;

    @track lstFilteredLead = [];

    @wire(getLeads) wiredLeads(result,error){

        if(result.data){

            this.lstLead  = result.data;

            for(let i=0; i<this.lstLead.length; i++){

                if(this.lstLead[i].LeadSource == 'Web') {

                    this.lstFilteredLead.push(this.lstLead[i]);

                }

            }

            

        } else {

            console.log(error);

        }

    }

}

filterRecordsInLWC.js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>51.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__RecordPage</target>

        <target>lightning__AppPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>

Output: