How To Use Javascript Promises with Lightning Components

Javascript Promises has been around for a while but only got the chance to use it on some of the aura component pieces I started working on.

In analogy you make a promise and either you fulfil or break your promise.

In Javascript Promises context these translate to “resolve” meaning promise is fulfilled or “reject” which means promise was broken and can be caused by an error.

A good use case for in Lightning is handling responses from asynchronous operations in which you pass a callback function. Then that callback function can make another asynchronous operation. Keep on nesting and you can easily eventually end with what they sometimes call callback hell as your code can be hard to manage.

Let’s dive into a creating Javascript Promise

I defined this as a helper method. It calls an apex method and depending on response and getState I mapped it to either resolve or reject.

Here I assigned a variable to the returned Promise in the javascript controller. The helper returns one parameter which is the response which I can access on the .then statement.

Here we called the p variable followed by a .then and the special callback function for Aura which is $A.getCallback. You can then chain another promise by calling and returning that promise. The next then can accept a parameter from the previous promise.

With Javascript Promises, this is more readable than a nested callback and easier to manage.

I hope you find this basic tip useful. Hit the comments below if you have questions.

How To Use Map Object In Aura Lightning Component

By Salesforce documentation, you can define several collection types including a Map.

A Map collection allows you have a key/value pair where the key is unique. Declaring such is easy by adding the following

<aura:attribute type="Map" name="fooMap" />

But in your controller, if you try to do any Map functions such as keys(), set(key, value), values(), you get an error such as:

set is not a function 

or

values is not a function.

What is happening in Lightning is even if you declared it as Map it is treated as an Object. It took me a while to figure this out.

To get around this “limitation” I manually assigned a map in the controller and then I was able to do Map functions. You can do this either on init or before you use the component Map.

Hope you find this tip useful.

How To Fix [Cannot read property ‘setParams’ of undefined] for Application Event in Aura Components

Component.cmp

    <aura:registerEvent name="CRMAppEvent" type="c:CRMAppEvent"/>

Controller.js

        var compEvent = $A.get("e.c:CRMAppEvent"); 
        compEvent.setParams({"type" : response})
        compEvent.fire();

Are you receiving cannot read property ‘setParams’ of undefined after assigning an event?

This indicates that $A.get(“e.c:CRMAppEvent”) cannot find the event and any reference to setParams method or any properties of the event would eventually be undefined.
To fix this you need to set your application event access to global

CRMAppEvent.evt

<aura:event type="APPLICATION" description="This is the generic Application Event" access="global">
    <aura:attribute name="type" type="String"/>
</aura:event>

Use of location.replace in Javascript

A quick tip: If you want to replace the current document and history from your browser. Use the window.location.replace() or location.replace().

Navigate back on your browser to see the difference.

window.location

window.location.replace

More Details: https://developer.mozilla.org/en-US/docs/Web/API/Window/location#Methods

Creating a Modal Popup Lightning Component

A quick tutorial on how to create a modal popup with Lightning Component.

What is modal popup?

Modal popup acts like a container for your content that displays on top of the content you are viewing. Imagine content stacked on top of it.

In short, a modal popup is a very handy way of showing content in front of your app.

How to build one in lightning?

  • First create lightning component and add a boolean attribute then default it’s value to false
  • On your controller, toggle the boolean value as you see fit based on events.
    • cancelBtn onclick event sets the displayModal value to true, thus displaying the modal.
    • yesBtn onclick event tied to the button navigates to another URL and sets the displayModal value back to false, thus hiding the modal popup

That’s it, you should have a working modal popup ready to go.

Final code is available here in GitHub

https://github.com/olopsman/lc-modal-popup

How to Validate forms built with Lightning Components

Learn how to validate lightning components forms easily.

I recently had a requirement to create a basic lightning component to capture form inputs. I previously had a not so good experience with building custom validation with Lightning components back in Summer17 when lightning was pretty new. I was using force:inputField and also used lightning:inputField.

Past few years it has become more efficient and easier with just the lightning:input field and default HTML5 APIs.

I have a simple bank form that captures and validates the form as such and when submitted validates the required fields.

Form

For the Bank Account Name input field specify the required attribute as true and check the validity of the field.

I use reportValidity to display the error message in the input field

And for the Bank Account Number input field aside from setting the field as true, I also specified a regular expression pattern. And then used the setCustomValidity function to display a custom error message.

And that folks, is how easy to validate the input form. Hit the comments below if you need help building your validation.

Recommended Books:

Ajax caching issue with IE workaround

If you’ve been developing websites I’m sure you pretty feel a little nausea from browser refreshing after an operation and prefer to work with AJAX for updating, deleting or loading some data from your DB with out the page reloading.

Most commonly used is http request is GET, your script runs flawlessly with Firefox, Chrome and Safari however on IE7 & and IE8 you don’t see the updates. This is because IE 7 and IE 8 treat GET request differently than POST, if there is no change from the last call it will always load up from it’s cache.

The workaround to the issue is pass an ever changing variable to the GET request like the current timestamp or date.

1. You can pass it on the ajax function call by adding an extra parameter time on the ajax call on the page.

ajaxify(x,<?php echo time(); ?>); // ajaxify(keywords, rand_time)

Then on your ajax function xmlHttp request call the rand_time parameter

xmlHttp.open(“GET”,”includes/ajax_page.php?dontcacheme=” + rand_time +”&keywords=”+keywords,true);

2. Or just create the random string using a Javascript Date class.

xmlHttp.open(“GET”,”includes/ajax_page.php?dontcacheme=” + new Date().getTime() +”&keywords=”+keywords,true);

This workaround worked well with my ajax scripts. Hope it helps.

Submit a Form using Enter Key

Here is a little Javascript I picked up. I run into a problem in IE wherein a form won’t submit when you hit the Enter key it just reloads itself but clicking the Submit button would processes your form. The form works with the Enter key fine in FF but not in IE.

Chances are that you maybe calling a function on your Submit button that will load the requested page? Something like this?

input type=”submit” name=”search” value=”Search” onClick=”myfunction();” >

Where in the myfunction() function can be anything like validating a page before it submits your data, or trigger another event or load an ajax request.

To fix this and allow using the Enter key to submit your form in IE. Create a new function in your Javascript like below which checks for the Enter key being pressed, keyCode == 13 then call your original event myfunction.

function checkEnter(e){
var characterCode
if(e && e.which){
e = e
characterCode = e.which
}
else {
e = event
characterCode = e.keyCode
}

if(characterCode == 13){
myfunction(); // onClick function you were loading on the submit button
return false
}
else{
return true
}
} // checkEnter

Then on one of the input fields call the onKeyPress event and call your new function.

input type=”text” name=”keywords” onKeyPress=”return checkEnter(event)” >