Stock Market Updates Lightning Component

Posted on Updated on

Hi All,

In this article, I will be showing you how to build a stock quote Lightning Component with HighChartTable chart and Yahoo’s YQL(Yahoo Query Language) web service.You can use this component to see Stock Market Updates of any Company and of any StockExchange provided by Yahoo API.Sometimes this API may not work like other APIs but do not worry it will start working.

YQL is like SOQL language that allows you to query, filter and combine data from multiple sources across both the Yahoo! network and other open data sources.Yahoo made things easy on us by providing a very intuitive console for accessing data via the API.You can read complete documentation about YQL.HighChartTable charts are used to represent your data as Charts and Graphs.HighChartTable chart can not be used for commercial purpose.

Screenshot_2015-08-12-19-40-00 Screenshot_2015-08-12-19-39-39

Send me an email on balkishan.kachawa@gmail.com for StockUpdates component package.

Installation Instructions

Follow the steps below to install the Stock Update component and create the application in your own Developer Org.

Step 1: Install the Component

  1. Enable Lightning Components in your new Developer Org:
    In Setup, click Develop > Lightning Components, check the Enable Lightning Components checkbox, and click Save.

Step 2: Enter Sample Data

  1. Click the StockSymbols tab and enter your favourite Company’s records with their Symbol and Stock Exchange Name.
    For example, enter the following values:

Salesforce :
Company : Salesforce,
Symbol : CRM
StockExchange : NYSE

Apple
Company : Apple,
Symbol : AAPL
StockExchange : NASDAQ

Google
Company : Google,
Symbol : GOOG
StockExchange : NASDAQ

Step 3: Add the StockUpdates Component to the Salesforce1 Menu

  1. In Setup, select Administer > Mobile Administration > Mobile Navigation
  2. Select StockUpdates in the Available list
  3. Click the Add button to add the StockUpdates tab to the Selected list
  4. Click the Up button to move the StockUpdates tab closer to the top of the menu and Click Save

Step 4: Test the Component in the Salesforce1 Application

  1. In Salesforce, remove the part of the URL that comes immediately after salesforce.com and append /one/one.app to the URL immediately after salesforce.com
  2. This starts the Salesforce1 Application simulator
  3. Click the menu button in the upper left corner
  4. Select Stock Updates in the menu
  5. Select any company from drop down list

Final result will look like this :

So That’s It Simple 🙂

Share Content on WhatsApp Using Lightning

Posted on Updated on

Hi All,

Whats-app is one of the most popular messaging apps in the world.One third of world’s population is using Whats-app on their smartphones.That is why I thought to implement a functionality by which user can share content on Whats-app. I implemented this with Salesforce1 Lightning.

I got this idea from here.
If you need complete code you can send me an email on balkishan.kachawa@gmail.com

In this demo I am showing you user’s feeds with WhatsApp Share button. When you click on this button it will ask you to share your specific feed with any contact in your mobile device. When complete it will look like this:
IMG-20150702-WA0002

Here is the complete code let’s walk through it :

FeedItemController.apxc
public class FeedItemController{
    @AuraEnabled
    public static List<FeedItem> getFeedItems(){
        return [SELECT Body FROM FeedItem WHERE InsertedById =: UserInfo.getUserId() ORDER BY CreatedDate DESC LIMIT 10 ];
    }
}

In this controller I have created a method getFeedItems() to return feeds of current logged in user.

WhatsAppLightningComponent.cmp
<aura:component controller="bklightning.FeedItemController" implements="force:appHostable">
	
    <ltng:require styles="/resource/whatsappfiles/whatsappfiles/bootstrap,
				/resource/whatsappfiles/whatsappfiles/whatsappbutton.css"
                  scripts="/resource/whatsappfiles/whatsappfiles/jquerymin.js" 
                  afterScriptsLoaded="{!c.afterLoaded}"></ltng:require>
    
    <aura:attribute name="feeds" type="FeedItem[]" />
    
    <div class="page-header page-header-anchor">
    	<h1>Share Your Feeds</h1>
    </div>
    <div id="msg" style="display:none;color:red">
    	Please share this article in mobile device
    </div>   
    <aura:iteration items="{!v.feeds}" var="feed">
        <div class="card">
          	<div class="card-heading">
            	{!feed.Body}
          	</div>
          	<div class="card-detail">
            	<a data-text="{!feed.Body}" class="whatsapp w3_whatsapp_btn w3_whatsapp_btn_large">Share</a>
        	</div>
        </div>
    </aura:iteration>
</aura:component>

Resources for this Lightning Component could be found here jQuery , Bootstrap.

WhatsAppLightningComponentHelper.js
({
	loadFeeds : function(component) {
		var action = component.get("c.getFeedItems");
        action.setCallback(this, function(a) {
            component.set("v.feeds", a.getReturnValue());
        });
        $A.enqueueAction(action);
	},
    
    whatsAppJS : function(component){
        var isMobile = {
            Android: function() {
                return navigator.userAgent.match(/Android/i);
            },
            BlackBerry: function() {
                return navigator.userAgent.match(/BlackBerry/i);
            },
            iOS: function() {
                return navigator.userAgent.match(/iPhone|iPad|iPod/i);
            },
            Opera: function() {
                return navigator.userAgent.match(/Opera Mini/i);
            },
            Windows: function() {
                return navigator.userAgent.match(/IEMobile/i);
            },
            any: function() {
                return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
            }
        };
    	
        jQuery('.whatsapp').click(function(){
            if( isMobile.any() ) {
 				var text = jQuery(this).attr("data-text");
                var message = encodeURIComponent(text);
                var whatsapp_url = "whatsapp://send?text=" + message;
                window.location.href = whatsapp_url;
            } else {
                jQuery('#msg').show();
            }
        })
    }
})

In WhatsAppLightningComponentHelper.js whatsAppJs() method is used to share content on Your WhatsApp.It can support any mobile device but we know that Lightning app is not supporting Android and other devices so it will not work for them.
I did not change code because I hope Lightning will support other Mobile Devices in future.

Please change Namespace to your Namespace before running this code.

Thanks 🙂

Lightning Wizard Component with jQuery and Bootstrap

Posted on Updated on

Hi All,

In this post I am sharing with you a Lightning Wizard Component built with Bootstrap and jQuery.
It is a multi step form wizard with Progress Bar and jQuery Validations.

IMG-20150623-WA0002 IMG-20150623-WA0005 IMG-20150623-WA0004

Requirements :
1) Download latest version of Bootstrap and jQuery.
2) “bklightning” namespace to “YourNamespace”.

Here is full code :

WizardDemoComponent.cmp
<aura:component controller="bklightning.CreateContactController" implements="force:appHostable">
    <ltng:require styles="/resource/wizarddemo/wizarddemo/bootstrap.min.css,/resource/wizarddemo/wizarddemo/style.css"
                  scripts="/resource/wizarddemo/wizarddemo/jquery.min.js,
                           /resource/wizarddemo/wizarddemo/jquery-ui.min.js,
                           /resource/wizarddemo/wizarddemo/jquery.validate.js,
                           /resource/wizarddemo/wizarddemo/bootstrap.min.js"
                  afterScriptsLoaded="{!c.afterLoaded}"/>
    
    <aura:attribute name="newContact" type="bklightning__ContactDetail__c"
                                        default="{ 'sobjectType': 'bklightning__ContactDetail__c'}"/>
    
    <div class="container">
    <br/><br/>
	<form class="form-horizontal form" id="form">
		<div class="col-md-8 col-md-offset-2">   	
			<div class="progress">
			  <div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
			</div>
		
			<div class="box row-fluid">	
				<br/>
				<div class="step">
					<div class="form-group">
						<label for="fname" class="col-sm-2 control-label">First Name</label>
						<div class="col-sm-10">
						  <input type="text" name="fname" value="{!v.newContact.bklightning__Firstname__c}" class="form-control" id="fname" placeholder="First Name"/>
						</div>
					</div>
					<div class="form-group">
						<label for="lname" class="col-sm-2 control-label">Last Name</label>
						<div class="col-sm-10">
						  <input type="text" name="lname" value="{!v.newContact.bklightning__Lastname__c}"  class="form-control" id="lname" placeholder="Last Name"/>
						</div>
					</div>
					<div class="form-group">
						<label for="email" class="col-sm-2 control-label">Email</label>
						<div class="col-sm-10">
						  <input type="text" name="email" value="{!v.newContact.bklightning__Email__c}" class="form-control" id="email" placeholder="email"/>
						</div>
					</div>			  
					  
				</div>
				<div class="step">
					<div class="form-group">
						<label for="phone" class="col-sm-2 control-label">Phone</label>
						<div class="col-sm-10">
						  <input type="text" name="phone" value="{!v.newContact.bklightning__Phone__c}" class="form-control" id="phone" placeholder="Phone"/>
						</div>
					</div>
					<div class="form-group">
						<label for="address" class="col-sm-2 control-label">Address</label>
						<div class="col-sm-10">
						  <textarea name="address" class="form-control" id="address" cols="10" rows="5" >{!v.newContact.bklightning__Address__c}</textarea>
						</div>
					</div>			  
					  
				</div>
				<div class="step display">
					<div class="form-group">
						<label for="company" class="col-sm-2 control-label">Company</label>
						<div class="col-sm-10">
							<input type="text" name="company" value="{!v.newContact.bklightning__Company__c}" class="form-control" id="company" placeholder="Company"/>
						</div>
					</div>
					<div class="form-group">
						<label for="numberofemp" class="col-sm-2 control-label">Number of Employees</label>
						<div class="col-sm-10">
							<input type="text" name="numberofemp" value="{!v.newContact.bklightning__NumberOfEmployee__c}" class="form-control" id="numberofemp" placeholder="Number of Employees"/>
						</div>
					</div>			  
					<div class="form-group">
						<label for="website" class="col-sm-2 control-label">Website</label>
						<div class="col-sm-10">
							<input type="text" name="website" value="{!v.newContact.bklightning__Website__c}" class="form-control" id="website" placeholder="Website"/>
						</div>
					</div>			  
				</div>
			
				<div class="row">
					<div class="showMsg" style="display:none;color:red;text-align:center;">
						<b>Your Information Saved Successfully</b><br/>
					</div>
				</div>
            
				<div class="row">
					<div class="col-sm-12">
						<div class="pull-right">
							<button type="button" class="action btn-sky text-capitalize back btn">Back</button>
							<button type="button" class="action btn-sky text-capitalize next btn">Next</button>
							<button type="button" onclick="{!c.saveContact}" class="action btn-hot text-capitalize submit btn">Submit</button>
						</div>
					</div>
				</div>			

			</div>
		
			</div> 
		</form> 
	</div>
</aura:component>

In WizardDemoComponent.cmp you can see I have used Latest Bootstrap and jQuery Library.
When all scripts loaded I am calling afterLoaded() function of WizardDemoComponentController.js.

WizardDemoComponentController.js
({
	afterLoaded : function(component, event, helper) {
        var current = 1;
        
        widget = jQuery(".step");
		btnnext = jQuery(".next");
		btnback = jQuery(".back"); 
		btnsubmit = jQuery(".submit");
        
        widget.not(':eq(0)').hide();
		
		helper.hideButtons(component,widget,current);
        helper.setProgress(component,widget,current);
        
        //Next Button Action
        btnnext.click(function(){
			if(current < widget.length){
				// Check validation
				if(jQuery(".form").valid()){
					widget.show();
					widget.not(':eq('+(current++)+')').hide();
					helper.setProgress(component,widget,current);
				}
			}
			helper.hideButtons(component,widget,current);
		})
        
        //Back Button Action
        btnback.click(function(){
			if(current > 1){
				current = current - 2;
				if(current < widget.length){
					widget.show();
					widget.not(':eq('+(current++)+')').hide();
					helper.setProgress(component,widget,current);
				}
			}
			helper.hideButtons(component,widget,current);
		})
		
		jQuery('.form').validate({ // initialize plugin
			ignore:":not(:visible)",			
			rules: {
				fname     : "required",
				lname     : "required",
				email    : {required : true, email:true},
				phone  : {required : true, number:true},
				address : "required",
				company : "required",
				website : {required : true, url:true},
				numberofemp : {required : true, number:true},
			},
	    });
        
	},
    
    saveContact : function(component, event, helper) {
        component.set("v.newContact.bklightning__Firstname__c",jQuery("#fname").val());
        component.set("v.newContact.bklightning__Lastname__c",jQuery("#lname").val());
        component.set("v.newContact.bklightning__Email__c",jQuery("#email").val());
        component.set("v.newContact.bklightning__Phone__c",jQuery("#phone").val());
        component.set("v.newContact.bklightning__Address__c",jQuery("textarea#address").val());
        component.set("v.newContact.bklightning__Company__c",jQuery("#company").val());
        component.set("v.newContact.bklightning__NumberOfEmployee__c",jQuery("#numberofemp").val());
        component.set("v.newContact.bklightning__Website__c",jQuery("#website").val());
        
        var newContact = component.get("v.newContact");
        
		helper.upsertContact(component, newContact); 	
        
        jQuery('.showMsg').show();
        jQuery('.form')[0].reset();
    }
    
})

In afterLoaded method of WizardDemoComponentController.js I am defining validations and click events.

WizardDemoComponentHelper.js
({
	setProgress : function(component,widget,currstep) {
		var percent = parseFloat(100 / widget.length) * currstep;
		percent = percent.toFixed();
		jQuery(".progress-bar").css("width",percent+"%").html(percent+"%");
	},
    
    hideButtons : function(component, widget,current) {
		var limit = parseInt(widget.length); 

		jQuery(".action").hide();

		if(current < limit) jQuery(".next").show();
		if(current > 1) jQuery(".back").show();
		if (current == limit) { 
			// Show entered values
			jQuery(".display label:not(.control-label)").each(function(){
				console.log(jQuery(this).find("label:not(.control-label)").html(jQuery("#"+jQuery(this).data("id")).val()));	
			});
			jQuery(".next").hide(); 
			jQuery(".submit").show();
		}	
	},
    
    upsertContact : function(component, newContact) {
        var action = component.get("c.createContact");
        action.setParams({
          "con": newContact
        });
        action.setCallback(this, function(a) {
        });
        $A.enqueueAction(action);
    }
})

In WizardDemoComponentHelper.js setProgress() and hideButtons() methods are used to set progress-bar and to hide buttons as wizard progresses.

So that’s it,Simple.

Leaflet.js,Map with Custom Images and Lightning Component

Posted on Updated on

Hi All,

In this post I am sharing with you a Lightning Map Component built with Leaflet.
Leaflet is an open source javascript library which you can find here.

pic1  pic2

Requirements :
1) Download latest version of Leaflet here.
2) “bklightning” namespace to “YourNamespace”.

Here is complete code let’s walk through it:

LightningMapComponent.cmp
<aura:component implements="force:appHostable">
	<ltng:require styles="/resource/leaflet/leaflet/leaflet.css" 
                  scripts="/resource/leaflet/leaflet/leaflet.js"
                  afterScriptsLoaded="{!c.afterJsLoaded}"/>
    
    <div id="map" style="width:100%; height: 100%"></div>
    
</aura:component>

In LightningMapComponent.cmp you can see I have used latest version of Leaflet Library. When all scripts loaded I am calling afterJsLoaded() function of LightningMapComponentController.js.

LightningMapComponentController.js
({
	afterJsLoaded : function(component, event, helper) {
        var map = L.map('map').setView([26.46, 74.64], 13);
        
        L.tileLayer('https://a.tiles.mapbox.com/v4/{YOUR MAP ID}/{z}/{x}/{y}.png?access_token=[YOUR ACCESS TOKEN]', {
            attribution: 'Balkishan @kachawaa'
        }).addTo(map);
        
        var LeafIcon = L.Icon.extend({
            options: {
                shadowUrl: '/resource/leaflet/leaflet/leaf-shadow.png',
                iconSize:     [38, 95],
                shadowSize:   [50, 64],
                iconAnchor:   [22, 94],
                shadowAnchor: [4, 62],
                popupAnchor:  [-3, -76]
            }
        });
        
        var greenIcon = new LeafIcon({iconUrl: '/resource/leaflet/leaflet/leaf-green.png'}),
            redIcon = new LeafIcon({iconUrl: '/resource/leaflet/leaflet/leaf-red.png'}),
            orangeIcon = new LeafIcon({iconUrl: '/resource/leaflet/leaflet/leaf-orange.png'});
        
        L.marker([26.46,74.64], {icon: greenIcon}).bindPopup("Ajmer Junction,Ajmer").addTo(map);
        L.marker([26.456221, 74.628175], {icon: redIcon}).bindPopup("Ajmer Sharif,Ajmer").addTo(map);
        L.marker([26.441522, 74.616850], {icon: orangeIcon}).bindPopup("Prithviraj Smarak,Ajmer").addTo(map);
    }
})

To use this Map Library you have to first register for your MAP ID and ACCESS TOKEN here.

LightningMap.app
<aura:application >
	<bklightning:LightningMapComponent />
</aura:application>

So that’s it.

WrapperClass in Lightning

Posted on Updated on

Hi All,

In my series of Salesforce1 Lightning posts today you will know, how to use Wrapper Class in Lightning?
There is a little difference when using Wrapper Class in Salesforce.com and Lightning.

When complete it will look like this :

pic1

Change “bklightning” namespace to “YourNamespace”.

If you need complete code you can download from github.

Let’s walk through code:

WClassController.apxc
public class WClassController{
    
    @AuraEnabled
    public static List<WrapperClass> getAccounts() {
        List<WrapperClass> wcList = new List<WrapperClass>();
        List<Account> accList = [SELECT Name,Active__c, (SELECT Name FROM contacts) FROM Account];
        
        if(accList.size() > 0){
            for(Account acct : accList){
                if(acct.contacts.size() > 0){
                    WrapperClass wc = new WrapperClass();
                    wc.count = acct.contacts.size();
                    wc.acc = acct;
                    wcList.add(wc);
                }
            }
        }
        
        return wcList;
    }
    
}

First off all you will notice that each method has an @AuraEnabled keyword.
Any method that you want to be visible to the Aura view components will need this keyword.

In WClassController.apxc controller getAccounts() method contains a WrapperClass List but you can not see WrapperClass in WClassController.apxc class.
Actually I have created a separate class for WrapperClass with the name WrapperClass.apxc.
Why I did so?
1)Because Apex Controller/Class Types cannot be marked as AuraEnabled.
2)If you create an inner class you can not access this class in Lightning components.
3)If you want to access members of Apex Controller through Object you need to marked them with @AuraEnabled keyword.

There is no difference when accessing the members of WrapperClass.

WrapperClass.apxc
public class WrapperClass{
    @AuraEnabled
    public Integer count;
    
    @AuraEnabled
    public Account acc;
    
}

In WrapperClass.apxc class you can see that I have marked each member of this class with @AuraEnabled keyword.
If you do not mark them @AuraEnabled,you will not be able to access them in Lightning Component.

WrapperClassComponent.cmp
<aura:component controller="bklightning.WClassController">
	<aura:attribute name="accounts" type="bklightning.WrapperClass[]"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <div>
        <table class="table table-bordered">
            <thead>
            	<tr>
                	<th><b>Name</b></th>
                    <th><b>Contact</b></th>
                    <th><b>Active</b></th>
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.accounts}" var="account">
                    <tr>
                        <td>{!account.acc.Name}</td>
                        <td>{!account.count}</td>
                        <td>{!account.acc.bklightning__Active__c}</td>
                    </tr>
                </aura:iteration>
            </tbody>
        </table>
    </div>
</aura:component>

In WrapperClassComponent.cmp component you can see I have used WrapperClass.apxc as “aura:attribute” Type.
To access an array/list of wrapper class you define “aura:attribute” Type like type=”bklightning.WrapperClass[]”.

So that’s it.Hope it will help you.

e-Signature App Using Lightning

Posted on Updated on

Hi All,
In my previous post I have shown you how we can convert currency of any country using lightning.
Today I will tell you how we can use HTML5 canvas to draw your signature and how we can attach this signature with your information in Salesforce lightning.

When complete it will look like this :

first

When you click on submit it will show you detail with your signature like this :

second

Changes :
1) Change “bklightning” namespace to “YourNamespace”.
2) Need to update browser as I am using HTML5, this App will work with Latest Version Browser.

If you need complete code you can drop me an email on this email id : balkishan.kachawa@gmail.com

Let’s walk through code:

ContactSignatureController.apxc
public with sharing class ContactSignatureController{
    
    @AuraEnabled
    public static void saveContact(ContactDetail__c con,String url) {
        String imgUrl = url.subStringAfter('base64,');
        
        insert con;
        
        Attachment attach = new Attachment();
        attach.contentType = 'image/png';
        attach.name = con.Firstname__c+' '+con.Lastname__c;
        attach.parentId = con.Id;
        attach.body = EncodingUtil.base64Decode(imgUrl);
        insert attach;
        
    }
    
    @AuraEnabled
    public static Attachment getAttachment(){
        return [Select Id,Name from Attachment order by CreatedDate DESC LIMIT 1];
    }
}

First off all you will notice that each method has an @AuraEnabled keyword.
Any method that you want to be visible to the Aura view components will need this keyword.

In ContactSignatureController.apxc controller saveContact() method is doing all work.
When you click on “Submit” button this method will be called.As you can see this method accepts two parameters:
First parameter is an object of ContactDetail which will have Contact Information.
Second parameter is an Encoded URL of image which we had drawn on canvas.We are using EncodingUtil.base64Decode() method to Decode URL.

ESignatureComponent.cmp
<aura:component controller="bklightning.ContactSignatureController" implements="force:appHostable">
    <aura:attribute name="att" type="Attachment"/>
    <aura:attribute name="newContact" type="bklightning.ContactDetail__c"
                                        default="{ 'sobjectType': 'bklightning__ContactDetail__c'}"/>
	
    <form>
    	<div class="form-group">
        	<label for="fname">First Name*</label>
          	<input type="text" class="form-control" id="fname" value="{!v.newContact.bklightning__Firstname__c}" autofocus="autofocus" onblur="{!c.doInit}" placeholder="First Name"/>
      	</div>
      	<div class="form-group">
        	<label for="lname">Last Name*</label>
          	<input type="text" class="form-control" id="lname" value="{!v.newContact.bklightning__Lastname__c}" placeholder="Last Name"/>
      	</div>
      	<div class="form-group">
        	<label for="phone">Phone*</label>
          	<input type="phone" class="form-control" id="phone" value="{!v.newContact.bklightning__Phone__c}" placeholder="Phone Number"/>
            <div id="pmsg" style="color:red"></div>
      	</div>
      	<div class="form-group">
        	<label for="signature">Your Signature*</label><br/>
          	<canvas id="signature" width="200" height="100" style="border:2px solid black"></canvas>
        </div>
        <div id="msg" style="color:red"></div>
      	<button type="button" class="btn btn-default" onclick="{!c.createContact}">Submit</button>&nbsp;&nbsp;
        <button type="button" class="btn btn-default" onclick="{!c.clearCanvas}">Clear Canvas</button>
    </form>    
    <div class="showDetail" style="display:none;">
        <b>Name &nbsp;&nbsp; : &nbsp;&nbsp;{!v.att.Name}</b><br/>
        <img src="{!'/servlet/servlet.FileDownload?file='+v.att.Id}"/>
    </div>
    
</aura:component>

In ESignatureComponent.cmp I am using HTML5 Canvas tag to draw signature.

When you click on “Submit” button it will call createContact() of ESignatureComponentController.js it then call saveContact() method of Apex Controller which will save Information and Signature.

So that’s it.

Currency Converter App Using Lightning

Posted on Updated on

The Salesforce Lightning Component Framework is the next-generation component based development framework for Salesforce.It is based on the Aura open source library and uses a mixture of JavaScript on the client and Apex on the Server. In this post I am using lightning to create a simple Currency Converter App.In this post I will not cover basics of lightning.To learn lightning basics you can download lightning pdf from here.

To convert currency i am using a free currency converter  Xignite API.You can also register for your free API here.

You can find complete code on github.

When complete it will look like this :

cc

Changes :
1) Change “bklightning” namespace to “YourNamespace”.
2) Register on Xignite to get you free API KEY.

Let’s walk through code:

CurrencyConverterControllerClass.apxc
public with sharing class CurrencyConverterControllerClass{
    
    @AuraEnabled
    public static List<CurrencyInformation__c> allCountries() {
        return [SELECT Id,Name,Code__c, Country__c FROM CurrencyInformation__c];
    }
    
    @AuraEnabled
    public static String getCurrency(String sourceCode,String targetCode) {
        String url = 'https://globalcurrencies.xignite.com/xGlobalCurrencies.json/GetRealTimeRate?Symbol=';
        url += sourceCode+targetCode+'&_token=YOURTOKEN';
        
        // Instantiate a new http object
        Http http = new Http();
        
        // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        
        HttpResponse res = new HttpResponse();
        
        // Send the request, and return a response
        if((sourceCode != null && sourceCode.trim().length() > 0) && (targetCode != null && targetCode.trim().length() > 0))
            res = http.send(req);
        else
            return null;
        
        Map<String, Object> response = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
        String text = (String)response.get('Text');
                
        return text;
    }
}

First off all you will notice that each method has an @AuraEnabled keyword.Any method that you want to be visible to the Aura view components will need this keyword. getCurrency() method calls out to the Xignite REST API with a GET request containing Source Country ,Target Country Code and API KEY.It will return response in JSON and the response JSON.deserialized into a Map and then into Text message.

CurrencyConverterComponentController.js
({
    doInit : function(component, event, helper) {
        helper.getCountries(component);
    },
    calculateCurrency : function(component, event, helper) {
        var srs = jQuery('#source option:selected').val();
    	var trg = jQuery('#target option:selected').val();
        helper.getResult(component, srs, trg); 	
    },
})

The CurrencyConverterComponentController.js implements the calculateCurrency() function called onclick of “Calculate” button in CurrencyConverterComponent.cmp and it calls the getResult() helper function.

CurrencyConverterComponentHelper.js
({
    getCountries : function(component) {
        var action = component.get("c.allCountries");
        action.setCallback(this, function(a) {
            component.set("v.countries", a.getReturnValue());
        });
        $A.enqueueAction(action);
        
	},
    getResult: function(component, srs, trg) {
        var action = component.get("c.getCurrency");
        action.setParams({
          "sourceCode": srs,
          "targetCode": trg
        });
      	action.setCallback(this, function(a) {
           	component.set("v.message", a.getReturnValue());
        });
        $A.enqueueAction(action);
    }
})

That getResult() helper function is defined in CurrencyConverterComponentHelper.js, and it calls the Apex getCurrency() function that actually does the REST API callout.It then takes the return value from that function, and populates the “message” attribute in the CurrencyConverterComponent.cmp component.

So that’s it. Simple! Coming soon with a new post on lightning.