Lightning Components contd..

Tags

,

In the previous post, we discussed about the Introduction of Lightning Components and now, we will create a Simple Lightning Component.

Prerequisite:

Before we create a Lightning Component, we need to make sure that My Domain is enabled in our Salesforce Org as it is Required to Use Lightning Components in Lightning component tabs, Lightning pages, the Lightning App Builder, or standalone apps. We will not cover this topic here and you can refer the link https://help.salesforce.com/articleView?id=domain_name_overview.htm&type=5 for more information.

Create a new Lightning Component:

Since we have already enabled MyDomain in our Salesforce Org, let us create a simple Lightning component to show all the Partner Accounts(Type=’Technology Partner’) in the drop down and we will also have a button called “Submit”, upon clicking on it, it will show the selected account. This Lightning Component will be added as a tab in Lightning Experience.

Output:

Tab accessed from All Items

Accounts sorted in asc order based on the account name:

Upon clicking on Submit button:

Steps to create a Lightning Component:

Step 1:

We will have to open Developer console and create a new Lightning Component Bundle

Step 2:

File -> New->Lightning Component

No spaces are allowed in the Name hence I have given ‘PartnerAccountsDisplay’ and given a meaningful description. I have not selected anything in the Component Configuration for now. Then, click on Submit button.

This creates a new ‘PartnerAccountsDisplay’ component bundle, with two open tabs. Close the first tab, and keep the PartnerAccountsDisplay.cmp tab open. We need to write our code in component editor between aura:component tags.

As we mentioned earlier, Lightning Component will have JavaScript(called as Client Side Controller) on the client side to handle validations, events, calling the apex class method and handle the response as well etc and on the server side, it is apex which will query all the Partner accounts in this case and send the output as a list to the Client Side Controller which will then be used to display them as options in the Combo-box(drop down).

Apex class:

global with sharing class ManageAccount {

    @AuraEnabled(cacheable=true)
    public static List<Account> GetAccount( String userId ) {
        String query;
        List<Account> accountList;
        query='SELECT Id,Name from Account WHERE Type=\'Technology Partner\' ORDER BY Name asc';
        accountList = new List<Account>();
        accountList = (List<Account>)Database.query(query);
        return(accountList);
    }
    
}

To make this method GetAccount available to our Lightning Component code (Client-Side Controller), there are two specific things done as given below:

  • The @AuraEnabled annotation before the method declaration.
  • The static keyword. All @AuraEnabled controller methods must be static methods, and either public or global scope.

PartnerAccountsDisplay.cmp

<aura:component access="global" implements="force:appHostable" controller="ManageAccount">
	<aura:attribute name="AccountSelectValue" type="String" default="" />
    <aura:attribute name="SelectOptions" type="List" />
   <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
                
                    <lightning:combobox aura:id="select" name="selectcombo" label="Technology Partner Accounts" 
                     required="true" value="{!v.AccountSelectValue}" options="{! v.SelectOptions }" style="background-color: #fceabd;"/>
    <lightning:button variant="brand" label="Submit" title="Base action" onclick="{! c.handleClick }"/>
                    
</aura:component>

What we have done in the Component code

  1. We have given global access for the component and implemented the interface “force:appHostable” as it is needed to allow the Component to be exposed as a custom tab in Lightning Experience. Also, we wire up the component to the server-side Apex controller(ManageAccount apex class).
  2. The <aura:handler> tag is used to handle any specific event and we are handling init event with the doInit action handler in our client side controller.
  3. We have created 2 attributes in the component, one of them(AccountSelectValue) is to store the selected value from the drop down and the other one(SelectOptions) is a list which stores all the drop down options retrieved by the apex class method GetAccount. Attributes on components are like instance variables in objects. We can set the Component attributes when we create it or during the Component lifecycle, in response to actions the user takes, or events that happen elsewhere and so on.
  4. Then, we have used lightning:combobox Base Lightning Component to create a dropdown with the values as names of the Technology Partner Accounts.
  5. We created a button by using lightning:button Base Lightning Component and clicking on it(onclick event), will call handleClick method in our client side controller.

P.S:if c. is used in the component, Salesforce will understand that it refers to the corresponding Client side Controller(js) and using c. in the Client Side controller will refer to the Server Side Controller(apex class). Also, note the usage of v. whereas v is something called a value provider. Basically, think of v as an automatic variable that’s made available for us to use to access Component’s attributes.

PartnerAccountsDisplayController.js(Client Side Controller)

({
	doInit : function(component, event, helper) {
		var action = component.get("c.GetAccount");
        //action.setParams({ userId : $A.get("$SObjectType.CurrentUser.Id") });
        action.setCallback(this, function(response){
            var state = response.getState();
            console.log('>>>>> state'+ state );
            if (state === "SUCCESS") {
            	console.log('======');
            	console.log(response.getReturnValue());
                var options = [];
                var allData = response.getReturnValue();
                console.log('resp',allData);
			    for(var x in allData){
			    	options.push({ value: allData[x].Name, label: allData[x].Name});
			    }
			    console.log('options : ',options);
			    component.set("v.SelectOptions", options);
	}
})
        $A.enqueueAction(action);
    },
    
    
    handleClick: function (cmp, event) {
        // This will contain the string of the "value" attribute of the selected option
        var selectedOptionValue = cmp.get("v.AccountSelectValue");
        alert("Selected Partner Account is: '" + selectedOptionValue + "'");
    }


});

What we have done in the Client Side Controller code:

  1. doInit – This action handler calls apex class method to load options for “Technology Partner Accounts” combobox. Calling the apex class method involves 3 steps:
  2. Create a remote method call – var action = component.get(“c.GetAccount”); -> This line of code creates a remote method call or remote action.
  3. Set up what should happen when the remote method call returns.-This is achieved in the next line of code, action.setCallback(…), is a block of code that will run when the remote method call returns.
  4. Queue up the remote method call. – $A.enqueueAction(action); adds the server call to the Aura component framework request queue. It, along with other pending server requests, will be sent to the server in the next request cycle.
  5. handleClick – This action handler is called when user click on Submit button. Here, we get the value of the attribute ‘AccountSelectValue’ which stores the selected value from the Technology Partner Account drop down and using alert, we show the value in the pop up.

Lightning Tab:

Finally, we created a Lightning tab as per the screenshot below to launch the Component.

We can talk about Lightning Design System and the Component Bundle such as Helper, Style, Documentation, Renderer, Design and SVG in the upcoming blog post.

I have given a very simple example of the Lightning Component as above and I have experience in building Simple, medium and complex Lightning Components including Lightning Communities for various clients. I am happy to help you to develop new Lightning Components and modify the existing Components based on the requirement. Please reach me at balabemdu@gmail.com for more information. Also, you can give your comments below reg any questions on this blog post.

Advertisements

Introduction to Lightning Components(Aura Components)

Tags

, ,

It has been a long time:) and lot happened in my personal life..Last year, I have been blessed with a baby boy :)…Let’s jump to the topic now..

Before we know about Lightning Component(LC), let’s talk about Lightning Component framework.

As per Salesforce, The Lightning Component framework is a modern UI framework for developing dynamic, responsive web apps for mobile and desktop devices. It uses JavaScript on the client side and Apex on the server side.

Advantages of Lightning Component Framework:

  • Framework comes with an Out-of-the-box Components for building apps
  • There are additional Lightning components available in the AppExchange, built by ISVs
  • Responsive design and cross browser compatibility
  • Event-driven architecture for better decoupling between components

So, what are Lightning Components or Aura Components?

Aura components are the self-contained and reusable units of an app.

A component can contain other components, as well as HTML, CSS, JavaScript, or any other Web-enabled code. This enables us to build apps with sophisticated UIs .

Base Lightning Components

The Lightning framework already has a set of prebuilt components and they are known as Base Lightning Components.

Now we know the definition of LC, there is also Base Lightning Components. What is it used for?

For instance, if we want to create a button, we don’t need to write code from scratch instead we make use of lightning:button base lightning component in our app and here lightning represents the namespace. The best part is we can configure the base component(meaning configure the given attributes etc) to form a new component in our app and it works seamlessly with desktop and mobile devices.

These base components handle the details of HTML and CSS for us too which makes it as light weight components. The whole list of component details are available in this component library link: https://developer.salesforce.com/docs/component-library/overview/components

Where can we use Lightning Components?

To see the lightning components in action in Salesforce, we need to launch it from either tabs or apps or actions:

Add LC as a Custom Tab in a Lightning Experience App

You can add Lightning Components as Custom Tabs by creating a Lightning tab under Setup->User Interface ->Tabs->Click New in the Lightning Component Tabs related list.

This image has an empty alt attribute; its file name is image-2.png

Once added as a tab, it will be available in All Items, if it is not added under Apps. If we create a new Lightning App under Setup -> App Manager | New Lightning App, it will be available in the App Launcher.

Note: We need to implement the force:appHostable interface(Out-of-box) in the aura:component tag on the Lightning component to allow it to be used as a custom tab in Lightning Experience or the Salesforce mobile app. I will create a LC in the next post which will be added as a custom tab in Lightning Experience.

Add LC as a Custom Tab in a Salesforce Mobile App

Create a custom Lightning component tab for the component under Setup->Tabs->Click New in the Lightning Tabs related list as described above.

Then, add your Lightning component to the Salesforce app navigation menu under Setup->Navigation->Salesforce Navigation. Once added, it will be displayed as a new menu item in the navigation menu in Salesforce mobile web.

Launch LC as a Quick Action

Create actions using a Lightning component under Setup->Objects->Account(for example)->Buttons and Links->Click on New Action button, and then add the action to an object’s page layout to make it instantly accessible from a record page.

Lightning componet quick action on record page

Note: We need to add the force:lightningQuickAction or force:lightningQuickActionWithoutHeader interface(Out-of-box) to an Aura component tag on the LC to enable it to be used as a custom action in Lightning Experience or the Salesforce mobile app.

Add LC to Lightning Pages

A Lightning Page is a custom layout that lets us design pages for use in the Salesforce mobile app or in Lightning Experience. There are three types of Lightning Page and they are App Page, Home Page and Record Page. They can be created under Setup->User Interface -> Lightning App Builder and we can add our Lightning component to the Page.

Override Standard Actions with Aura Components

We can override the View, New, Edit, and Tab standard actions on most standard and all custom objects. One such example for account edit action override is given below:

Note: We need to implement the lightning:actionOverride interface(Out-of-box) to an Aura component tag on the LC to enable it to be used as a Override action in Lightning Experience.

Also, Lightning Components can be added to:

  1. The stand alone app which would use the Salesforce data and available independently from the standard Salesforce environment.
  2. Visualforce pages
  3. The external site (for example, Sharepoint or SAP), or even elsewhere on the platform such as on Heroku using Lightning Out feature.

In the next post , I will create a simple Lightning Component and demonstrate its capabilities. Until then, see you!!

P.S. If you have any questions about this post, please give your comments below.

Duration of the events in the Salesforce calendar can’t go beyond 14 days

Tags

I have faced this issue recently in my current project [Later on, I realized that I was aware of this issue earlier perhaps 3 yrs ago when I was working in the consulting firm, my bad memory:)]. The requirement is to create the calendar event when the record is created in one of our Custom object based on the start and end date fields in it.

I created a process builder and it gets triggered when the new record is created in the Custom object. Immediate action in the process builder is to create a record in Event object.

It works fine when the difference in start and end date is less than or equal to 14 days (duration of the event is less than or equal to 14 days) else it throws an error ”

Vote for the below idea so that salesforce removes this limit in the calendar event:

https://success.salesforce.com/ideaView?id=08730000000Guw6AAC

Workaround: I created a flow to create events based on the start and end date. Suppose, start and end date span for 6 months(Start date=15/5/2018 and End date=15/11/2018), split them into 14 days and create events accordingly. So, in this case, I would have created 13 event records approximately from 15/5/2018.

Please comment below for any questions on this.

Tip # 25: Error in creating Lookup relationship

Tags

Recently, when I tried creating a lookup relationship with the Product (Standard Object) from the custom object, I got the below error though I was not trying to create the Master Detail relationship:

You cannot create a new Master-Detail relationship on an existing custom object if records already exist. You must first create a Lookup relationship, populate the lookup field with data in all records, and then change the relationship type to Master-Detail.

Moreover, the custom object was a new object and it did not have any records. I was bit confused and the error message is misleading as well. Then, after googling, it looks like you can create a lookup field to Product only if you allow to clear the field if the Product record is deleted(please check the below screenshot for your reference):

Lookuperror

Please let me know for any clarification.

Tip # 24: Password issue in ANT

I was using ANT Migration tool to deploy the components(e.g. Layouts, classes etc) from my machine to Sandbox last week. But, for some reason, though I have given the correct user name and password in build.properties file, it was giving me authentication error(Invalid username, password, security token; or user locked out).  I tried the same user name and password to log into Salesforce Sandbox using browser, I could login into it successfully. This looked very strange to me and then I found out the issue:

my password had two $ signs and for some reason, ANT was not able to recognise them. After, I changed the password by excluding the $ signs, it worked.

I thought of sharing this as it would help someone who face this issue since I had to spend about an hour to figure out the issue.

 

Salesforce Certified Platform Developer I

Recently, I cleared my Salesforce Platform Dev I exam and following are the tips from my side to clear the exam:

  1. If you have access to a Premier Online Training catalogue or Partner Training catalogue, you can go through the Cert Prep video from Salesforce and it will definitely be a very good starting point and will brush up your skills on the topics given in the exam guide . Link for the video – Certification Preparation for Platform Developer I
  2. Go through the questions given in SfdcStudy , Propofs and  Salesforcesteps
  3. Please note that some of the answers for the questions given in the above links might not be correct hence double check by googling or post them in comments section and I will try to answer them.

P.S: I found this link from the net today and I believe that it could be useful too https://quizlet.com/133435950/flashcards

Tip# 23 – Why this error message System.QueryException: Non-selective query against large object type?

Recently, in the project that I am working on, we have received this error in our apex code and this error occurs when querying large objects using SOQL (particularly for queries inside triggers). In our case, SOQL is inside the TriggerHandler which is called by the trigger.

Developers receive this error message when a non-selective query in a trigger executes against an object that contains more than 200,000 records. To avoid this error, ensure that the query is selective.

The performance of a SOQL will depend on the presence of a selective filter(in WHERE Clause). If a SOQL query contains at least 1 selective filter, the query is said to be selective. If the SOQL query doesn’t contain a selective filter, the query is said to be un-selective and will require a full table scan.

How to determine if the query is selective?

  • A query is selective when one of the query filters is on an indexed field and the query filter reduces the resulting number of rows below a system-defined threshold.
  • The selectivity threshold is 10% of the first million records and less than 5% of the records after the first million records, up to a maximum of 333,333 records.

Example:

  1. SELECT Id FROM Account WHERE Id IN (<list of account IDs>)

Since the filter is on the ID field which is a standard and Primary Key field, it will have an index created at the DB. If SELECT COUNT() FROM Account WHERE Id IN (<list of account IDs>)returns fewer records than the selectivity threshold, the index on Id is used. This index is typically used when the list of IDs contains only a few records.

2. SELECT Id FROM Account WHERE Name != ”

Since Account is a large object even though Name is indexed (primary key), this filter returns most of the records, making the query non-selective.

3. SELECT Id FROM Account WHERE Name != ” AND CustomField__c = ‘ValueA’
Here we have to see if each filter, when considered individually, is selective. As we saw in the previous example, the first filter isn’t selective. So, let’s focus on the second one. If the count of records returned by SELECT COUNT() FROM Account WHERE CustomField__c = ‘ValueA’ is lower than the selectivity threshold, and CustomField__c is indexed, the query is selective.

For more information:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_VLSQ.htm

https://help.salesforce.com/articleView?id=000002493&type=1

Also, there are lot of links in stack exchange which discusses this issue and you can refer them as needed: https://salesforce.stackexchange.com/search?q=Non-selective+query