Show record city Temperature on record detail page in Salesforce.

Posted on September 23, 2021 Post Thumbnail

Yo Trailblazers,

In this blog post, I'm going to create a lightning component which shows temperature of record city on record detail page.

Check following image for demo.

image

What you'll Learn from Blog Post :)

1. How to make callout to rest api from Apex.

2. Parse returned response using Apex.

Walkthrough :)

1. First we need to get Api Key from https://openweathermap.org/current

2. Add https://openweathermap.org to Remote sites in Salesforce.

3. Than, we require current record id.

4. With the help of record id, query city.

5. At the end, We need to make callout and show temperature on record page.

Let's Start :)

I'm going to use account object for this task.

1. First we need to get Api Key from https://openweathermap.org/current

For this you need to sign up, 

If you don't want to sign up, Use my API Key:

String Api key = '5236dbbf932439eef162fb321536f5e7';

2. Add https://openweathermap.org to Remote sites in Salesforce.

Setup > Remote Site Settings

Remote

Now, Let's create Apex Class.

public class AccountWeatherClass {
    @AuraEnabled
    public static list<String> getTemprature(String AccountId) {
        String city;
        String endpoint = 'https://api.openweathermap.org/data/2.5/weather?q=';
        String apikey = '5236dbbf932439eef162fb321536f5e7';
        city = [SELECT Id, billingcity FROM Account Where Id =:AccountId].billingcity;
        String mainUrl = endpoint + city + '&appid=' + apikey + '&units=metric';
        system.debug(mainUrl);
        list<String> resList = new list<String>();
        String temp;
        String temp_max;
        String temp_min;
        Http h = new Http();
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint(mainUrl);
        req.setMethod('GET');
        
        HttpResponse res = h.send(req);
        System.debug('response:--> ' + res.getBody());
        
        JSONParser parser =  JSON.createParser(res.getBody());
        while (parser.nextToken() != null) {
            if(parser.getText() == 'temp') 
            {
                System.debug('temp'+ parser.getText());
                system.debug('Main temp_max-->' + parser.nextValue());
                temp = parser.getText();
                
                resList.add(temp);
            }
            if(parser.getText() == 'temp_max') 
            {
                System.debug('temp_max'+ parser.getText());
                system.debug('Main temp_max-->' + parser.nextValue());
                temp_max = parser.getText();
                
                resList.add(temp_max);
            }
            if(parser.getText() == 'temp_min') 
            {
                System.debug('temp_min'+ parser.getText());
                system.debug('Main temp_min-->' + parser.nextValue());
                temp_min = parser.getText();
                resList.add(temp_min);
            }
        }
        String fieldName = parser.getCurrentName();
        //system.debug(resList);
        return resList;
    }
}

In above getTemprature method, I'm passing account Id as parameter and on the base of Account Id Querying City.

And with the help of city and api key, Making callout.

Getting following response:

{"coord":{"lon":77.2167,"lat":28.6667},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"stations","main":{"temp":28.05,"feels_like":32.71,"temp_min":28.05,"temp_max":28.05,"pressure":1009,"humidity":83},"visibility":2500,"wind":{"speed":4.63,"deg":130},"clouds":{"all":75},"dt":1632369062,"sys":{"type":1,"id":9165,"country":"IN","sunrise":1632357596,"sunset":1632401233},"timezone":19800,"id":1273294,"name":"Delhi","cod":200}

 After getting a response, I'm creating parser using

JSONParser parser = JSON.createParser(res.getBody());

And filtering required values such as temp, temp_min, temp_max and returning these values.

Now, Let's create Aura component

AccountWeather.cmp

<aura:component controller="AccountWeatherClass" implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> 
    <aura:attribute name="temp" type="String"/>
    <aura:attribute name="temp_min" type="String"/>
    <aura:attribute name="temp_max" type="String"/>
    <lightning:card iconName="standard:account" title="Real time Temprature">
        
        <p class="slds-p-horizontal_small">
            <h1>Account City Temp : {!v.temp} Celsious</h1> 
            <h1> Account City Max Temp : {!v.temp_max} Celsious</h1> 
            <h1> Account City Min Temp : {!v.temp_min} Celsious</h1>
        </p>
    </lightning:card>
</aura:component>

AccountWeatherController.js

({
	doInit : function(component, event, helper) {
		var accId = component.get("v.recordId");
        //console.log(accId);
        var action = component.get("c.getTemprature");
        action.setParams({
            "AccountId":accId
        });
        action.setCallback(this, function(response) {
            //console.log(response.getReturnValue());
            var res = response.getReturnValue();
            component.set("v.temp",res[0]);
            component.set("v.temp_max",res[1]);
            component.set("v.temp_min",res[2]);          
        });
        $A.enqueueAction(action);
    }
})

After creating above component add it to account record page.

img

If you have any question Ask Me

Thanks for Reading :)

Write a comment for suggestions and hit the heart icon.


341
0

Tags: #lightningComponent #httpCallout

Comments

There are no comments yet.
Your message is required.

Get notified of new posts