How To Validate Lightning Component forms In Flow Screens

If you are looking to learn how to validate custom lightning components forms in a flow screen then hopefully this post could shed some light on what can be accomplished and the solutions implemented around it.

So far, I found it straight forward to add a custom lightning component in a flow screen, simply specify that you are implementing the “lightning:availabelForFlowScreens” and the component becomes an available element in the flow screen.

Should appear as an option under the Custom heading of the Screen Elements.

However, adding validation for the form inputs in the lightning component with flow screens is a tricky subject with all the limitations of the “out of the box” functionalities.

My requirements are following:

  • capture user information
  • fields are displayed based on user inputs
  • and fields are mandatory
  • only when mandatory fields are completed can you proceed to the next screen
  • ability to navigate back and update any fields.

So far my screen looks like per screenshot when first question is answered Yes.

Hitting next just straight goes to the next screen without any validation.

To allow us to do some sort of validation, we would use the Aura.Action attribute type. As per documentation.

An Aura.Action is a reference to an action in the framework. If a child component has an Aura.Action attribute, a parent component can pass in an action handler when it instantiates the child component in its markup.

Can’t find further documentation, but the way I understand it, in the context of flows, the flow screen acts as the parent component and we can call the function in the lightning component by declaring the attribute.

The type Aura.action returns the following object.

isValid: Boolean – stops the flow from going to the next screen.
errorMessage: String – custom error message.

To make this work we also need to add the action handler init. The ”Next” button on flow screens calls the action handler but only on init. (Why on init only? I still don’t fully understand.) Hitting next forces the lightning component to rerender and call init, from init we can set the validate object.

From your controller.js Set the component “v.validate”.

Without any inputs, if I hit Next.

Yey! So far validation works!

Let’s add some more validation logic.

When I answer questions and leave some blank. I get several issues with this validation.

  • when the component rerenders
    • any custom hide/show logic would be lost
    • any inputs are lost
  • validation error location is at the bottom of the screen
  • you can only show one error at a time

To get around these limitations, I ended up building some custom validation handling, with a combination of flow variables to persist data, design attributes for input/output, sessionStorage to track missing fields inputs, and fieldCustomValidity and if you have date fields or combobox you may need to use afterRender calls.

First update the .design file for the input fields that needs to persists. To keep it easy we use one attribute per field.

Next create flow variables for each attribute and checkbox is available for input and output set to true.

Here is the final attributes

Next assign each to the custom lightning component input and output.

Now for the new validation logic. First I created an array for mandatoryFields. For each field required I add aura:id to the array.

Next I iterate to the array of fields and check if it has been populated with a value. For each missing value I again add to a new array called missingFields.

Next I check the length of the missing fields and I store the information in a sessionStorage.

SessionStorage is like localStorage but it gets cleared up when the session ends. (will cover storing of data locally on another topic)

Then I call the return statement setting isValid to false and an empty errorMessage(this property is required to display errors on the page).

So when Next action is called, it runs the init and sets the sessionStorage.

Note that I’m using the renderer. As adding a date field threw me off a little as the DOM is not yet ready after init and you are trying to access them checking for missing inputs. Solution was to put in the afterRender. But if you only have the basic input fields, you can have the code in the init as well.

I call helper method which displays the error by reading the sessionStorage for missing fields and I set the fieldCustomValidity.

And my flow is looking sharper, I am prompted for incomplete fields and I can move to next when complete and go back and update if I need to.

Code for this is posted on my github repo.

I’ll be posting a video tutorial as well soon. Stay tuned.

Hope someone find this post useful. Happy coding!

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>

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: