Sunday, April 8, 2018

Salesforce Lightning: Fetch data from an external API using Ajax


We will be using a very simple API which takes a GET request formatted as a certain URL, returning some random Chuck Norris jokes...lol, without requiring Apex code. So user will enter a number, and on click of Search button, will make a request to http://api.icndb.com/jokes/random/ API, get the response, parse it and display it on the page.

<aura:application extends="force:slds">

    <aura:attribute name="number" type="Integer" default="5"/>
    <aura:attribute name="html" type="String"/>

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

        <h2 class="slds-text-heading_large">Chuck Norris Jokes Generator</h2>

        <lightning:input type="number"
                         aura:id="number"
                         label="Enter a number"
                         class="slds-m-around_small slds-size_1-of-8"/>

        <lightning:button variant="brand"
                          label="Get Jokes"
                          class="slds-m-around_medium"
                          onclick="{!c.handleClick }"/>

        <aura:unescapedHtml value="{!v.html}"/>

    </div>

</aura:application>
({
    handleClick : function(component, event, helper) {
        const number = component.find('number').get('v.value');

        if (number) {
            component.set('v.number', number);
            helper.handleAjaxRequest(component, event, helper);
        }

    }
})
({
    handleAjaxRequest : function(component, event, helper) {
        const xhr = new XMLHttpRequest();

        const number = component.get('v.number');

        const url = 'http://api.icndb.com/jokes/random/' + number;

        xhr.open('GET', url, true);

        xhr.onload = function() {
            if(this.status === 200) {
                const response = JSON.parse(this.responseText);

                let output = '<ul class=\'slds-list--dotted\'>';

                if(response.type === 'success') {
                    response.value.forEach(function(joke){
                        output += `<li>${joke.joke}</li>`;
                    });
                }

                output += '<ul>';
                component.set('v.html', output);
            }
        };

        xhr.send();
    }
})

The XHR object has properties and methods associated with it, one of which is open, where we specify type of request we want to make and the URL we want to make it to. The 3rd parameter is set as true as we want to make it asynchronous. The rest of the code is self-explainable.

As a last step, we need to add http://api.icndb.com as a trusted site or else our Lightning component will not be able to make a request and you will notice an error message in console something like this: Refused to connect to 'https://api.icndb.com/jokes/random/6' because it violates the following Content Security Policy directive:....."

So navigate to Setup → CSP Trusted Sites, and add the following entry.


That's it. Enjoy the jokes.

Now authentication is required for a lot of external APIs which are intricate ones using OAuth, and that can get complicated. So just remember that not all APIs give you as much freedom as they do here. You normally have to register your application with their systems and then you will have to authenticate. Different rules, different APIs.
Share This:    Facebook Twitter

Wednesday, March 28, 2018

Customize lightning:combobox (picklist) component using only CSS

The code below will create a dropdown list of selectable options. This code is taken from the Lightning documentation:
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/aura_compref_lightning_combobox.htm

<aura:application extends="force:slds">
    <aura:attribute name="statusOptions" type="List" default="[]"/>

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

    <div class="slds-size--1-of-4 slds-p-around--large">

        <lightning:combobox aura:id="selectItem" name="status" label="Status"
                            placeholder="Choose Status"
                            value="new"
                            onchange="{!c.handleOptionSelected}"
                            options="{!v.statusOptions}"/>

    </div>

</aura:application>
({
    loadOptions: function (component, event, helper) {
        var options = [
            {value: "new", label: "New"},
            {value: "in-progress", label: "In Progress"},
            {value: "finished", label: "Finished"}
        ];
        component.set("v.statusOptions", options);
    },

    handleOptionSelected: function (component, event) {
        var selectedOptionValue = event.getParam("value");
        console.log(selectedOptionValue);
    }
})

This is how it looks:

To hide the text label (Status), override this css class slds-form-element__label, and set display property as none. You can also set the variant attribute of this component as label-hidden.

As per the current implementation, this component doesn't support selection of multiple options. So there is no need of displaying the check-icon besides the option values. To hide this icon, override this css class slds-listbox__icon-selected and set display property as none. This is how the picklist looks now:

Now when the dropdown list is visible, we notice that the arrow icon is still pointing downwards. Let's manipulate this icon so that it points upwards in this scenario. For this, add a transform property to this element and rotate 180 degrees, like below:
.THIS .slds-dropdown-trigger.slds-is-open .slds-combobox__form-element .slds-icon {
    transform: rotate(180deg);
}

This is how it looks now:

Now let's change the background color of selectable options on hover.
.THIS .slds-dropdown-trigger.slds-is-open .slds-listbox__option.slds-has-focus {
    background-color: cyan;
}

This is how it looks now:

Notice the blue border glow around the read-only inputbox. You can change this color to cyan like below:
.THIS .slds-input:focus, .THIS .slds-input:active {
    border-color: cyan;
    box-shadow: 0 0 3px cyan;
}

This is how the lightning:combobox looks now, quite a simple one:

Finally, this is how the CSS style resource looks like:
.THIS .slds-form-element__label, .THIS .slds-listbox__icon-selected  {
    display: none;
}

.THIS .slds-dropdown-trigger.slds-is-open .slds-combobox__form-element .slds-icon {
    transform: rotate(180deg);
}

.THIS .slds-dropdown-trigger.slds-is-open .slds-listbox__option.slds-has-focus {
    background-color: cyan;
}

.THIS .slds-input:focus, .THIS .slds-input:active {
    border-color: cyan;
    box-shadow: 0 0 3px cyan;
}


Share This:    Facebook Twitter

Tuesday, February 13, 2018

Salesforce Lightning: What browser am I using? What version is my browser?


You can use $Browser global value provider to return information about the hardware and operating system of the browser accessing the application as described in the link below:
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/expr_browser_value_provider.htm

But it cannot be used to detect the browser type or version number.

You can use the below code to detect the browser on which you are running your Lightning application. Here, I am checking whether I am on Internet Explorer or not:

checkBrowser: function (component) {

    var browserType = navigator.sayswho= (function(){
        var ua= navigator.userAgent, tem,
            M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if(/trident/i.test(M[1])){
            tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
            return 'IE '+(tem[1] || '');
        }
        if(M[1]=== 'Chrome'){
            tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
            if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
        }
        M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
        if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
        return M.join(' ');
    })();
    if (browserType.startsWith("IE")) {
        component.set("v.isIE", true);
    }
}

If the value of isIE attribute is true, then you are running on Internet Explorer. Similarly you can check for Chrome, Firefox, Opera and other browsers.
Share This:    Facebook Twitter

Thursday, January 4, 2018

Lightning: Star rating component


This is a simple, highly customizable star rating component.

Attributes:
value: this is the actual value which represents the value of rating
readonly: when set to true, the rating cannot be edited.

To use this component:
<c:StarRating value="2" readonly="false"/>

Refer the github link for the code:
https://github.com/iamsonal/Star-Rating
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top