Wiring the client-side to the server using Apex controllers

So far, we have learned how to write client-side JavaScript controllers and helpers. In this section, we will learn how to wire client-side calls to the server-side Apex. Apex is an object-oriented programming language similar to Java. Apex allows you to write database logic and queries such as stored procedures. This section assumes that the reader is familiar with Salesforce Apex programming.

In your Salesforce org, whitelist Google APIs via Remote Site Settings for the following application so that your org can reach out to the YouTube API. The navigation path is Setup| Security | Remote Site Settings

The following screenshot shows the Remote Site Settings:

The code to search YouTube results from the YouTube REST API follows here. The instructions for registering the API key can be obtained here: https://developers.google.com/youtube/v3/getting-started.

Use Visual Studio IDE and create an Apex class. The class consists of http callout to search YouTube based on the search string provided. The code for this is as follows:

public with sharing class Youtubesearch {

public static final string key = '<your API key>';//Replace with your API key here

public static final string youtubesearchURL = 'https://www.googleapis.com/youtube/v3/search?key='+key+'&part=snippet';

@AuraEnabled
public Static String search(String searchstr){
// Instantiate a new http object
Http h = new Http();
// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
HttpRequest req = new HttpRequest();
String url = youtubesearchURL+'&q=' + EncodingUtil.urlencode(searchstr,'UTF-8');
//String url = youtubesearchURL;
req.setEndpoint(url);
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
//system.debug('RESULTS..>>>'+YoutubeDataParser.parse(res.getBody()));
//return YoutubeDataParser.parse(res.getBody());
return res.getBody();
}

}

Notice that we have annotated variables and methods with the @auraEnabled annotation. While working with Lightning Components, it's important to note that to call server-side methods from the client-side JavaScript, the method should be annotated with the @auraEnabled annotation, and also notice that any property of the Apex class that needs to be exposed to the Lightning Component framework needs to have this annotation.

To wire, the server-side code to the client-side JavaScript, let's use the JavaScript controller and helper we built in the prior section.

The code to enqueue the server-side action is as follows:

  1. Add the Apex controller that your helper will be calling to the Component Markup using the controller attribute. The code for this as follows:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" controller="YoutubeSearch">
  1. To hold the results obtained from the server, we require an attribute at the frontend. This is defined as follows, shown in bold:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" controller="YoutubeSearch">
<aura:attribute name="searchTerm" type="String" />
<aura:attribute name="data" type="Map"/>
  1. The JavaScript controller invokes the helper on the Search button click is as follows:
({
handleClick : function(component, event, helper) {
helper.setSearchTerm(component, event);
}
})

  1. The helper that invokes the server-side search method is shown as follows. Notice how we take the response from the server and assign it to the attribute (using component.set()):
({
setSearchTerm : function(component, event) {
var searchTerm = component.find('searchBox').getElement().value;
console.log(searchTerm);
component.set("v.searchTerm",searchTerm);
// create a one-time use instance of the search action
// in the server-side controller
var action = component.get("c.search");
action.setParams({ searchstr : searchTerm});
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var youtube_res = JSON.parse(response.getReturnValue());
console.log(response.getReturnValue());
console.log(youtube_res);
component.set("v.data",youtube_res);

}
else if (state === "INCOMPLETE") {
// do something
}
else if (state === "ERROR") {
var errors = response.getError();
if (errors) {
if (errors[0] && errors[0].message) {
console.log("Error message: " +
errors[0].message);
}
} else {
console.log("Unknown error");
}
}
});
$A.enqueueAction(action);
}
})
  1. The code in the callback function is shown as follows. It sets the data attribute to hold a response object from a server. Notice that we also parse the JSON string into the JavaScript object using JSON.parse():
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var youtube_res = JSON.parse(response.getReturnValue());
console.log(response.getReturnValue());
console.log(youtube_res);
component.set("v.data",youtube_res);
}
});
If you are not familiar with the callback function, I recommend reading the following article: https://developer.mozilla.org/en-US/docs/Glossary/Callback_function .
  1. Finally, let's enhance the frontend markup code to iterate and show the results. The following is the final code for the markup. Notice that the newly added code is highlighted. The code for the youtubesearch.cmp file is as follows:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" controller="YoutubeSearch">
<aura:attribute name="searchTerm" type="String" />
<!--ATTRIBUTES DECLARATION -->
<aura:attribute name="data" type="Map"/>
<div class="c-container">
<Lightning:layout multipleRows="true" horizontalAlign="center" verticalAlign="center">
<Lightning:layoutItem flexibility="auto" size="6">
<div class="slds-form-element">
<label class="slds-form-element__label" for="text-input-id-1">Enter search term</label>
<div class="slds-form-element__control">
<input type="search" id="text-input-id-1" class="slds-input" placeholder="Enter Search Term" aura:id="searchBox"/>
</div>
</div>
</Lightning:layoutItem>
<Lightning:layoutItem flexibility="auto" size="4" padding="horizontal-small">
<Lightning:button variant="brand" label="Search" title="" onclick="{! c.handleClick }" class="c-btn"/>
</Lightning:layoutItem>
<Lightning:layoutItem flexibility="auto" padding="around-large" size="6">
<p> You searched for {!v.searchTerm} </p>
</Lightning:layoutItem>
<Lightning:layoutItem flexibility="auto" padding="horizontal-small" size="8">
<aura:iteration items="{!v.data.items}" var="cardItem">
<Lightning:card title="{!cardItem.snippet.title}">
<p class="slds-p-horizontal_small">
{!cardItem.snippet.description}
</p>
<div class="slds-media__figure">
<a href="{!'https://www.youtube.com/watch?v='+cardItem.id.videoId}" target="_blank">
<img src="{!cardItem.snippet.thumbnails.high.url}" style="height:100px;" alt="Placeholder" />
</a>
</div>
</Lightning:card>
</aura:iteration>
</Lightning:layoutItem>
</Lightning:layout>
</div>
</aura:component>
  1. If you have an end-to-end working application, the output screen will be as follows. To preview, use the test application URL. The URL will be https://<myDomain>/c/youtubeSearchApp.app. This assumes that you have created a Lightning App Bundle from the Developer Console named youtubeSearchAppas discussed earlier:
  1. Let's look at the following diagram, which summarizes the chain of actions and events from the user interaction on the client-side code to the server-side call:

The diagram shows the chain of events and actions that takes place from the browser to the server when a Lightning Component loads or an action is performed. The diagram mentions an init event. The init event is the event that is raised by the component when the component loads (you can treat this as being similar to an onload event ). The syntax for the init event is as follows:

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

Notice that, via the action, we can invoke the controller function just as we invoked the search function on the button click.

The value="{!this}" setting marks this as a value event. You should always use this setting for an init event.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.200.14