Monday, March 30, 2020

Component to fetch and display Country-wise COVID19 Data in Lightning Web Component


                 Note: The Data is being fetched from the public API (Click here for reference). 




Components:

Covid19Data - Apex class for making callouts.
covid19LWC - Lightning Web Component for displaying the data from the callout.
Endpoint_Covid19 - Remote Site Settings to enable our Salesforce org to make callouts to the desired endpoint.
COVID 19 Data - Lightning Tab to accommodate covid19LWC.


-------------------- Covid19Data.apxc -----------------------

public class Covid19Data {

    @AuraEnabled(cacheable=true)
    public static List<wrapperData> getCovid19SummaryData(){
        
        List<wrapperData> returnVal = new List<wrapperData>();
        
        http h = new http();
        httprequest req = new httprequest();
        req.setEndpoint('https://api.covid19api.com/summary');
        req.setHeader('Accept', 'application/json');
        req.setMethod('GET');
        req.setTimeout(12000);
        
        httpresponse res = h.send(req);
        
        if (res.getStatusCode() == 200) {
            Map<String, Object> responseResult = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
            List<Object> objects = (List<Object>) responseResult.get('Countries');
            for(Object obj : objects){
                wrapperData wrapperObj = new wrapperData();
                String strResult = JSON.serialize(obj);
                wrapperObj = (wrapperData) JSON.deserialize(strResult, wrapperData.class);
                if(String.isNotBlank(wrapperObj.Country)) returnVal.add(wrapperObj);
            }
        }
        return returnVal;
    }
    
    public class wrapperData{
        @AuraEnabled
        public string Country;
        @AuraEnabled
        public integer NewConfirmed;
        @AuraEnabled
        public integer TotalConfirmed;
        @AuraEnabled
        public integer NewDeaths;
        @AuraEnabled
        public integer TotalDeaths;
        @AuraEnabled
        public integer NewRecovered;
        @AuraEnabled
        public integer TotalRecovered;
    }
}


Tuesday, February 4, 2020

Guided Action in Salesforce

Guided Actions, in Lightning, help a user to get more insights while working on a complex business process and such that the data being captured is per the requirements and also, when more than one user/team (group/queue) are working on the same record one after the other.

Guided Actions are added under the component name - "Actions & Recommendations" in Lightning App Builder.
NOTE: This doesn't show up on Home Page



The Guided Action is invoked through Process Builder by creating a record of type RecordAction, the type can be a QuickAction or a Flow (we are dealing with Flow type here):
The various fields used are:
Action : Flow API Name
Action Type : Flow (Used) / QuickActions
Order : the order in which you want to show the Action type (when more than one Guided Action is to be shown)
Parent Record Id : The record on which the flow actions  would be saved on completion
Hide/Remove Action in UI : When False, user doesn't have the option to Hide the Action from Page
Pinned : To pin the action on UI
Is Mandatory : This comes up with an Asterisk mark before the Action, shown as Mandatory, when True.


When the condition is met, the Guided Action shows the Flow type on UI, as below:




Tuesday, December 10, 2019

Generate Random String in Apex

public static String generateRandomString() {
        final String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        String randStr = '';
        while (randStr.length() < 5) {
           Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length());
           randStr += chars.substring(idx, idx+1);
        }
    system.debug('Value----'+randStr); 


    }

Thursday, November 21, 2019

Get current user Info :

Lightning Controller : var currentUserId = $A.get("$SObjectType.CurrentUser.Id");

Apex : User userObj = [SELECT Id, Name, UserName FROM User WHERE Id =:userInfo.getUserId()];

Friday, November 15, 2019


Assign Tasks to different members in a Queue using RoundRobin technique

Integer IntrandomNumber = Integer.valueof((Math.random() * 1000));
for{
 Group grp = [SELECT Id, Name, Type, (SELECT Id, UserOrGroupId,   GroupId FROM GroupMembers) FROM Group WHERE DeveloperName ='<Name_of_queue>' AND Type =: 'Queue' LIMIT 1];

  if(grp != null && grp.GroupMembers != null &&       !grp.GroupMembers.isEmpty()){
  Integer userIndex = Math.mod(IntrandomNumber,       grp.GroupMembers.Size());
  task.OwnerId = grp.GroupMembers.get(userIndex).UserOrGroupId;
}
IntrandomNumber = IntrandomNumber+1;

}

Wednesday, October 30, 2019

Custom Notifications in Lightning

Sometimes we come up with the scenario when we need to assign Tasks to multiple users or users from the Queue or Groups.
But this functionality is not available in Configuration, i.e. Point-and-Click, so achieve this we need to go for code (link).
Idea can be found at Link.

The Lightning experience has a solution : 
The Lightning experience comes up with a functionality called - Custom Notifications under Setup --> Home.



Let us say, we have a requirement in an organization that Sales team (the team members might be a part of a public group or a queue) needs to be notified (through task, not possible without code, or using Custom Notifications in Lightning) whenever the Stage is Prospecting.

This can be achieved using Process Builder :



Once "Send Custom Notification" is selected, give some value in the Action Name. The Notification Type populates the value of the Custom Notification created earlier on Setup -> Home page.


The Notification Type gives us the ability to assign the Custom Notification to a variety of User types, ranging from Owner, User to Group, Queue, Account Team, Opportunity Team.




Sunday, September 29, 2019

Preview Files/Attachments in Lightning Web Components (LWCs)

--------------------- TestClass.cls --------------------------

//to fetch all files in an org
@AuraEnabled(cacheable=true)
public static List<ContentDocumentLink> getFiles(){
    return [Select Id, ContentDocumentId From ContentDocumentLink];
}

//to fetch files related to a specific record
@AuraEnabled(cacheable=true)
public static List<ContentDocumentLink> getFilesFromSpecificRecord(sObject sObjId){
    return [Select Id, ContentDocumentId From ContentDocumentLink WHERE LinkedEntityId =:sObjId];
}

------------------- fetchFilesFromOrg.js -----------------
/* eslint-disable no-console */
/* eslint-disable no-unused-vars */

import { LightningElement, track , wire} from 'lwc';
import { NavigationMixin, CurrentPageReference } from 'lightning/navigation';
import getFiles from '@salesforce/apex/TestClass.getFiles';

export default class fetchFilesFromOrg extends NavigationMixin(LightningElement) {
@track data;
        @wire(getFiles,{})
        rec({error,data}){
         if(data){
            var result =[];
            for(var i=0; i<data.length; i++){
                result.push(data[i].ContentDocumentId);
            }
            this.data=result;
         }if(error){
             console.log("error while fetching files from org");
         }
        }

navigateToWebPage(event) {
var fileId = event.target.title;
this[NavigationMixin.Navigate]({
                type: 'standard__namedPage',
                attributes: {
                    pageName: 'filePreview'
                },
                state : {
                   selectedRecordId: fileId
                }
              })
}
}
}

------------------ fetchFilesFromOrg.html -----------------------

<template>
<lightning-card>

<template for:each={data} for:item='item'>
<tr key={item.Id}>
<td><a> <lightning-formatted-rich-text  title={item} value={item} onclick={navigateToWebPage}></lightning-formatted-rich-text> </a></td>
</tr>
    </template>

</lightning-card>
</template>

This shows up like this: