How to Get Custom Label Value in Lightning Component?

Custom Label in Salesforce is text that will be covert to any language that Salesforce support. To access Custom Label in Lightning Component use following syntax.

<ui:outputText value=”{!$Label.c.LabelName}”/> where is namespace. Default namespace of an org is c. If you have created a namespace myapps, then your code to access custom label is {!$Label.myapps.LabelName}

If you have created a Custom Label which name is description, then your code in lightning component is {!$Label.c.description}.

In JavaScript controller or helper you can get custom label value $A.get(“{!$Label.c.description}”)

var desc = $A.get(“{!$Label.c.description}”);

Lightning:helpText Comonent in Lighting Out

There is some issue of CSS classes in lightning out if you are using <lightning:helpText> in lightning out. Here we are providing some CSS classes to use in your Cisualforce page.

Let’s create a lightning component which use <lightning:helpText> component named helpTextInLightningOut.cmp.

<aura:component>
<lightning:helptext
content=”The tooltip displays on the lower left of the icon or above the icon if space is available. It automatically adjusts its position according to the viewport.”
/>
</aura:component>

Create a Visualforce page to use above created lightning component. In your Visualforce page use <style> tag and  paste following CSS style.

.slds-popover__body,
.slds-popover__footer,
.slds-popover__header {
	position: relative;
	padding: .5rem .75rem;
	word-wrap: break-word
}

.slds-popover {
	position: relative;
	border-radius: .25rem;
	width: 20rem;
	min-height: 2rem;
	z-index: 6000;
	background-color: #fff;
	display: inline-block;
	box-shadow: 0 2px 3px 0 rgba(0, 0, 0, .16);
	border: 1px solid #d9dbdd
}

.slds-popover--tooltip,
.slds-popover_tooltip {
	width: auto;
	max-width: 20rem;
	background: #16325c;
	border: 0
}
.slds-popover--tooltip .slds-popover__body,
.slds-popover_tooltip .slds-popover__body {
	font-size: .75rem;
	color: #fff
}

.slds-fall-into-ground {
	visibility: hidden;
	opacity: 0;
	transform: translate(0, 0);
	transition: opacity .1s linear, visibility .1s linear, transform .1s linear;
	will-change: transform
}

.slds-nubbin--bottom-left:before,
.slds-nubbin_bottom-left-corner:before,
.slds-nubbin_bottom-left:before {
	width: 1rem;
	height: 1rem;
	position: absolute;
	transform: rotate(45deg);
	content: '';
	background-color: inherit;
	bottom: -.5rem;
	margin-left: -.5rem
}

.slds-nubbin--bottom-left:after,
.slds-nubbin--bottom-left:before,
.slds-nubbin_bottom-left-corner:after,
.slds-nubbin_bottom-left-corner:before,
.slds-nubbin_bottom-left:after,
.slds-nubbin_bottom-left:before {
	left: 1.5rem;
	top: 100%;
	margin-top: -.5rem
}

.slds-nubbin--bottom-left:after,
.slds-nubbin_bottom-left-corner:after,
.slds-nubbin_bottom-left:after {
	box-shadow: 2px 2px 4px 0 rgba(0, 0, 0, .16);
	z-index: -1
}

.slds-popover :last-child {
	margin-bottom: 0
}

If you used above style in your Visualforce page, then Lightning:helpText component also work properly in lightning out same as it work in lightning community or in Salesforce lightning interface

Output:

Learn more about lightning:helpText click here.

 

Apex Action Function In Visualforce Page

You can call apex action function in visualforce page. We can use AJAX functionality in Visualforce page without writing JavaScript. We write an apex class DemoCtrotroller.cls and a Visualforce Page Demo. In following example getting related one Contact and one Opportunity of Account. There also a Account picklist and on change event getting contact and opportunity asynchronously.

Example of Apex Action Function

:
DemoCtrotroller.cls

public with sharing class DemoCtrl {
    public Account acc{get;set;}
    public Contact con{get;set;}
    public Opportunity opp{get;set;}
    public List accList{get;set;}
    public String selectedAcc{get;set;} 
        
    public DemoCtrl()
    {
        accList = new List();
        for(Account a : [Select id,Name from Account order by Name ASC])
        {
          accList.add(new SelectOption(a.Id,a.Name));    
        }
        
        List acc1 = [Select id,Name,Rating,Phone from Account order by Name ASC limit 1];
        List con2 = [Select id,FirstName,LastName,MobilePhone,Email from Contact Where AccountId=:acc1[0].Id limit 1];
        List opp2=  [Select id,Name,StageName,Probability from Opportunity Where AccountId=:acc1[0].Id limit 1];
        if(acc1.size()>0)
        {
            acc = acc1[0];
        }
        else
        {
            acc = new Account();
        }
        if(con2.size()>0){
          con = con2[0];    
        }
        else
        {
            con = new Contact();
        }
        if(opp2.size()>0){
            opp = opp2[0];
        }
        else
        {
            opp = new Opportunity();
        }

    }
    
    public PageReference changeAccount()
    {
        List acc1 = [Select id,Name,Rating,Phone from Account Where Id=:selectedAcc];
        List con2 = [Select id,FirstName,LastName,MobilePhone,Email from Contact Where AccountId=:selectedAcc limit 1];
        List opp2=  [Select id,Name,StageName,Probability from Opportunity Where AccountId=:selectedAcc limit 1];
        
        if(acc1.size()>0)
        {
            acc = acc1[0];
        }
        else
        {
            acc = new Account();
        }
        if(con2.size()>0){
          con = con2[0];    
        }
        else
        {
            con = new Contact();
        }
        if(opp2.size()>0){
            opp = opp2[0];
        }
        else
        {
            opp = new Opportunity();
        }
        return null;
    }   
}

Demo.page

<apex:page controller="DemoCtrl" sidebar="false">    
    <apex:form >
        <apex:actionFunction action="{!changeAccount}" name="methodOneInJavascript" rerender="alldetail">
            <apex:param name="accid" assignTo="{!selectedAcc}" value="" />
        </apex:actionFunction>
        <apex:sectionHeader title="Demo" />
        <apex:pageBlock >
            <apex:selectList value="{!selectedAcc}" size="1" onchange="methodOneInJavascript(this.value)">
                <apex:outputLabel >Select Account: </apex:outputLabel>
                <apex:selectOptions value="{!accList}"/>                
            </apex:selectList>
        </apex:pageBlock>
        <apex:pageBlock title="Account, Contact and Opportunity" id="alldetail">
            <apex:pageBlockSection title="Account Detail" columns="2">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel >Account Name:</apex:outputLabel>
                    <apex:outputField value="{!acc.Name}" label="Account Name"/>
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                    <apex:outputLabel >Phone:</apex:outputLabel>
                    <apex:outputField value="{!acc.Phone}" label="Phone" />
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                    <apex:outputLabel >Rating:</apex:outputLabel>
                    <apex:outputField value="{!acc.Rating}" label="Rating" />
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>            
        
            <apex:pageBlockSection title="Contact Detail" columns="2">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel >First Name:</apex:outputLabel>
                    <apex:outputField value="{!con.FirstName}" label="First Name" />
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                    <apex:outputLabel >Last Name:</apex:outputLabel>
                    <apex:outputField value="{!con.LastName}" label="Last Name" />
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                    <apex:outputLabel >Cell Phone:</apex:outputLabel>
                    <apex:outputField value="{!con.MobilePhone}" label="Cell Phone" />
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>            
       
            <apex:pageBlockSection title="Opportunity Detail" columns="2">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel >Opportunity Name:</apex:outputLabel>
                    <apex:outputField value="{!opp.Name}" label="Opportunity Name" />
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                    <apex:outputLabel >Stage Name:</apex:outputLabel>
                    <apex:outputField value="{!opp.StageName}" label="Stage Name" />
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                    <apex:outputLabel >Probability:</apex:outputLabel>
                    <apex:outputField value="{!opp.Probability}" label="Probability" />
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>            
        </apex:pageBlock>
        
    </apex:form>
</apex:page>

Output:
Apex Action Function

SOQL Injection in Apex Salesforce

An SOQL Injection in Apex is computer attack to steal data from your database. Hence this is important to prevent SOQL Injection in Apex while writing query to select data from database. In Apex you can write Select query in two ways.
1. Inside brackets like [].

Example:- If you want to get all contact where name end with xyz. Then your select query will be like

String likeStr='%xyz';

List<Contact> conList = [Select Id,FirstName,LastName from Contact Where name like : likeStr];
System.debug(conList);

In this type of query Salesforce by default apply SOQL Injection. We do not required to explicit write extra code for SOQL Injection in Apex class
OUTPUT

(Contact:{Id=0037djdddkdkdkdk, FirstName=Andy, LastName=xyz})

2. Database.query() or Database.countQuery().

Example:- If you want to get all contact where name end with xyz. Then your select query will be like

String likeStr='%xyz';

List<Contact> conList = Database.query('Select Id,FirstName,LastName from Contact Where name like \''+String.escapeSingleQuotes(likeStr)+'\'');

System.debug(conList);

Note:

Focus on dynamic query which are build by concatenate multiple string and use Escaping Single Quotes for all variable used in query. For escaping single quotes use simple static method of String class(String.escapeSingleQuotes(variableName)).

FLS Check in Apex Class

In an apex class you should check Field Level Security. Most of us do not check. This is best practice to explicitly check security before any database statement like SELECT, INSERT, UPDATE AND DELETE. If you create an app to for AppeExchange then it is must for your app. For example if a user have access to read all contact but not able to create or modify record. So you also have to check is logged in user able to create or update record in your apex class.

Learning FLS in apex class by steps

1. Check for Object is accessible or not means if you want to get account name and phone. Then your should be like

if(Schema.SObjectType.Account.isAccessible()) // Object Accessibility 
{
   //Fields Accessibility
   if(Schema.SObjectType.Account.Fields.Name.isAccessible() && Schema.SObjectType.Account.Fields.Phone.isAccessible())
   {
        List<Account> accList = [Select Name,Phone from Account Limit 1];
   }
}

2. Check create permission if you want to insert account record.

if(Schema.SObjectType.Account.isCreateable()) // Object Accessibility 
{ 
    //Fields Accessibility 
    if(Schema.SObjectType.Account.Fields.Name.isCreateable() && Schema.SObjectType.Account.Fields.Phone.isCreateable()) 
    { 
          Account accObj = new Account(Name='Test',Phone='1234567890');
    } 
}

NOTE 1: Do not write SOQL query without LIMIT or Where Clause.
In your SOQL query write where clause like [Select id from contact where name =’test’].
[Select id from contact LIMIT 1];

Generic Code to Insert Record in Object Salesforce

// Get object type by passing object name
Schema.SObjectType objType = Schema.getGlobalDescribe().get(objectName);

// Create instance of sObject
sObject genericObj = objType.newSObject();

//Set fieldValue for each fields, you want to set
//@param:fieldApiName must be of String type
//@param:fieldValue of any data type value
genericObj.put(fieldApiName,fieldValue);

//Insert record by Insert statement
Database.insert(genericObj, true);

Use Standard Controller In Visualforce Page

How to use standard controller in Visualforce Page?

Using Standard Controller we easily insert update and delete record from custom Visualforce Page.

To associating Standard Controller with Visualforce Page use standardController attribute of <apex:page> tag.

To associate custom Object controller use custom object:-

<apex:page standardController=”Custom_Object_Name__c”>

To associate standard Object controller use standard object, suppose you want to bind with Lead object this your code will:-

<apex:page standardController=”Lead”>

Let’s try to save a lead using standard controller. There are some point need to focus during using standard controller:-

  1. Use <apex:pageMessages/> tag insde <apex:form> tag. This tag handle messages like error or warning.
  2. You must include all required fields in your form.
  3. Use any one action from (save,quicksave,delete,edit,cancel and list)
  4. In case of save action if record created successfully then controller redirect to record detail page.
  5. Use command button, action support or action function  to bind with a action(save,quicksave,delete,edit,cancel and list)
<apex:page standardController="Lead" showHeader="true" sidebar="true">
	<apex:form>
		<apex:pageMessages/>
		<apex:outputLabel>Last Name</apex:outputLabel>
		<apex:inputField id="lastName" value="{!lead.LastName}"/>
		<apex:outputLabel>Company Name</apex:outputLabel>
		<apex:inputField id="company" value="{!lead.Company}"/>
		<apex:commandButton action="{!save}" value="Save" />
	</apex:form>
</apex:page>

Output of above code will be

Standard Controller In Visualforce Page

In Lead and Contact  object Last name is mandatory(required) field. Also in Lead Object Company name is required. Click save button without enter field data. You will get error message  like following

Standard Controller In Visualforce Page

Encrypt and Decrypt String in Apex Salesforce

In apex class you can use EncodingUtil and Crypto classes to encrypt and decrypt string in apex class.

Useful methods of EncodingUtil to encode and decode string in apex class.

  1. String base64Decode(String inputString)
  2. String base64Encode(Blob inputBlob)
  3. Blob convertFromHex(String inputString)
  4. String convertToHex(Blog inputBlob)
  5. String urlDecode(String inputString, String encodingScheme)
  6. String urlEncode(String inputString, String encodingScheme)

Note: for URL encode and decode second parameter will be encoding scheme i.e., UTF-8. All methods are static so you can call by class name.

Example of all above methods to encode and decode string

base64Encode() and base64Decode

Blob blobData=Blob.valueOf('salesforce xyz');

// Encode 'salesforce xyz' String using base64
String encodedString = EncodingUtil.base64Encode(blobData);
System.debug(encodedString);
//output: c2FsZXNmb3JjZSB4eXo=

//Just use decode method to decode above encoded string
Blob decodeString = EncodingUtil.base64Decode(encodedString);
system.debug(decodeString.toString());
//output: salesforce xyz

convertToHex and convertFromHex() methods

Blob blobData=Blob.valueOf('salesforce xyz');

// Encode 'salesforce xyz' String using base64
String encodedString = EncodingUtil.convertToHex(blobData);
System.debug(encodedString);
//output: 73616c6573666f7263652078797a

//Just use decode method to decode above encoded string
Blob decodeString = EncodingUtil.convertFromHex(encodedString);
system.debug(decodeString.toString());
//output: salesforce xyz

if you want to test above code go to developer console press Ctr + E. A anonymous window will be open. Paste code in anonymous box and click execute button.

Encrypt and Decrypt String in Apex

In same way you can encode and decode url using urlEncode() and urlDecode() methods of EncodingUtil class.

Encrypt and Decrypt String in Apex Using ManagedIV

Encrypt and Decrypt String in Apex using ManagedIV. ManagedIV encryption and deryption required an security key of 16 bits. Use 16 bits security key for both encoding and decoding. If you want to get decoded data as string you can use toString() method of Blob class. Want to learn more about encode and decode string in Salesforce click next two linkencodingutil and Crypto classes.

public class MyEncodingUtil
{
	// Security key must be 16 characters string
	public static key='[email protected]%sAfk';

	public static String encodeString(String encodingString)
	{
		Blob blobData = Crypto.encryptWithManagedIV('AES128', key, Blob.valueOf(encodingString));
		return EncodingUtil.base64Encode(blobData);
	}
	public static String decodeString(String str)
	{
		Blob blobData = EncodingUtil.base64Decode(str);		
		Blob decryptedBlob = Crypto.decryptWithManagedIV('AES128', key, encodedEncryptedBlob);		
		return decryptedBlob.toString();   
	}
}

All Salesforce DX Commands List

Salesforce  provide Command Line Interface to increase productivity with integrated tools. Using this tool(Salesforce DX) you can create SF Org, apex class, lightning component, visualforce page and so on. You have to download and install tool  on you local machine. Please use following table to download Salesforce DX tool. Reference from https://trailhead.salesforce.com

OSDownload URL
Windows 32-bithttps://sfdc.co/sfdx_cli_win
Windows 64-bithttps://sfdc.co/sfdx_cli_win64
macOShttps://sfdc.co/sfdx_cli_osx
Debian/Ubuntu 64https://sfdc.co/sfdx_cli_linux
Debian/Ubuntu x86https://sfdc.co/sfdx_cli_linux_x86

Whenever finish installation open you command window to test sfdx command

Note: All command example from Window OS
C:\Users\ADMIN>sfdx
If Salesforce DX installed on your system above command will produce following output
Salesforce DX
C:\Users\ADMIN>sfdx help force when you run this command this command return all command list that support by Salesforce DX.

All command suffix by sfdx command

Command NameDescriptionExample
force:apexWork with Apex code

Syntax will be like –> sfdx force:apex:class:create n class_name d forceapp/main/default/classes

-n means required component name

-d means required directory path where component created in local machine

force:apex:class:create (create an Apex class)
force:apex:execute (execute anonymous Apex code)
force:apex:log:get (fetch a debug log)
force:apex:log:list (list debug logs)
force:apex:log:tail (start debug logging and display logs)
force:apex:test:report (display test results)
force:apex:test:run (invoke Apex tests)
force:apex:trigger:create (create an Apex trigger)
force:authAuthorize an org for use with the Salesforce CLI force:auth:web:login
force:configConfigure the Salesforce CLI force:config:get (get config var values for given names)
force:config:list (list config vars for the Salesforce CLI)
force:config:set (set config vars for the Salesforce CLI)
force:dataManipulate records in your org
force:docDisplay help for force commands
force:lightningCreate and test Lightning component bundles
force:limitsView your org’s limits
force:mdapiRetrieve and deploy metadata using Metadata API
force:orgManage your Salesforce DX orgs
force:packageInstall and uninstall first- and second-generation packages
force:package1Develop first-generation managed and unmanaged packages
force:package2Develop second-generation packages
force:projectSet up a Salesforce DX project.force:project:create -n your-proect-name
force:schemaView standard and custom objects
force:sourceSync your project with your orgs.

pull only source code into your local machine from your configured ORG which are not sync.

push only unsync source code form local machine to configured ORG

 force:source:pull 

force:source:push

force:userPerform user-related admin tasks force:user:create (create a user for a scratch org)
force:user:display (displays information about a user of a scratch
org)
force:user:list (lists all users of a scratch org)
force:user:password:generate (generate a password for scratch org users)
force:user:permset:assign (assign a permission set to one or more users of
an org)
force:visualforceCreate and edit Visualforce page force:visualforce:component:create (create a Visualforce component)
force:visualforce:page:create (create a Visualforce page)
force:aliasManage username aliases force:alias:list (list username aliases for the Salesforce CLI)
force:alias:set (set username aliases for the Salesforce CLI)

 

Set default dev hub username

Note: Here you can get error if you running above some commands. For Example let’s try to create org from scratch use command: sfdx force:org:create -s -f config/project-scratch-def.json -a your-org-name
ERROR: No defaultdevhubusername org found.

Above error will be fixed by sfdx force:config:set [email protected] –global

After setting default username of your development hub org now you are able to run command to create dev org from scratch. Now you can use a command to open new created org by C:\Users\ADMIN\your-project-dir>sfdx force:org:open (this command return an url to open your created org without login)

Use Salesforce DX command to create Apex Class AND Lighting Component

1. Let’s create lightning Component by CLI using sfdx command
C:\Users\ADMIN\your-project-dir>sfdx force:lightning:component:create -n cmp_name -d force-app/main/default/aura (-n means required component name and -d means required directory path where component created in local machine)

2. Let’s create Apex class by CLI using sfdx command

C:\Users\ADMIN\your-project-dir> sfdx force:apex:class:create n class_name d forceapp/main/default/classes

Comment please if you like this post.

Exception Handling And Save Log In Salesforce Object

Exception Handling is the best practice of robust app development and maintenance. In your project if you want to handle exception in proper way and save log in custom object. Then you can create a helper class(“ExceptionHandler“) and an custom object (“Error_Log__c“). What info you can log? You can log class name, method name, username, log time and error description.

So you custom object fields are::

Field LabelApi NameField TypeSize
Class Nameclass_name__cText255
Method Namemethod_name__cText255
Userusername__cLookup(User)
Log Timelog_time__cDateTime255
Error Descriptiondescription__cTextArea(Long)32000
Line NumberLine__cText6
HTTP Status CodeHTTP_Status_code__cText7

1. Log Apex Call-Out Error:

public class ExceptionHandler
{
    public static void logApexCalloutError(String className,String methodName,String lineno,HttpResponse response)
    {
	Error_Log__c log = new Error_Log__c();
	log.className__c = className;
	log.methodName__c = methodName;
	log.lineno__c = lineno;
	log.log_time__c=System.now();
	log.user__c = UserInfo.getUserId();
	
	// You can get HTTP Status Code and Response Body
	if(response!=null)
	{
		log.description__c=response.getBody();
		log.HTTP_Status_code__c =response.getStatusCode();			
	}
	Insert log;		
     }	
}

2. Exception Handling of Insert and Update Statements

If you insert or update record in bulk using Database.Insert() or Database.upsert() statement then use following method to save log. I think Salesforce Data Loader also use this technique to show insert and update result. But using following code you can log only failed record detail.

public class ExceptionHandler
{
    public static void logInsertORUpdateError(String className,String methodName,String lineno,List<Database.UpsertResult> saveResultList)
    {
        // In Error Log Custom object you can add an extra column Object name to save also object name
	List<Error_Log__c> logList = new List<Error_Log__c>();
        Transient Database.UpsertResult upsertResult;
        for (Integer index = 0; index < saveResultList.size(); index++) {        
                upsertResult = saveResultList[index];                                    
                //Use isSuccess() method of Database.UpsertResult class to is record inserted/updated or not
                if (!upsertResult.isSuccess()) {                    
                    Error_Log__c log= new Error_Log__c();                    
                    log.description__c = String.valueOf(upsertResult.getErrors()[0].getMessage());
                    log.className__c = className;
	            log.methodName__c = methodName;
	            log.lineno__c = lineno;
	            log.log_time__c=System.now();
	            log.user__c = UserInfo.getUserId();
                    if(upsertResult.getId() != null){
                        log.Object_Name__c = upsertResult.getId().getSobjectType().toString();
                    }
                    logList.add(log);                    
                }
          }
          if(!logList.isEmpty())
          {
               Database.insert(logList);
          }	
    }
}

Log insert error:

Above method only work for Database.upsert() statement. If you want to log Database.insert() statement errors too. Then you can write same code and change parameter List<Database.UpsertResult> by List<Database.InsertResult>.

You can call logInsertORUpdateError() method like –>

List upsertResObjList = upsert(recordToUpsert, externalIdField, allOrNone);
ExceptionHandler.logInsertORUpdateError('clsname',methodname,'212',upsertResObjList);

To learn more about Database statements please click here

Set Default Assignment Rule To Case and Lead Object

This is very easy using trigger to set default assignment rule to case and lead object. First you need to create an assignment rule on Case and Lead object.
Let’s create an assignment rule
Go-to Case Assignment Rules–> click on New button–> Enter Rule Name “Assignment Rule 2” –> make Active by checkbox and click Save button.
Set Default Assignment Rule To Case and Lead Object

There will be only one assignment rule active for an object. In simple way you can said that other assignment rule become inactive if your new created assignment rule become active.

Now let’s create an apex trigger to set assignment rule

trigger setAssignmentRuleTrigger on Case (after insert)
{   
    if(trigger.isInsert){
        List arRuleList = new List();
        List caseList = new List();
        
        arRuleList = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];
        
        if(!arRuleList.isEmpty())
        {
            for(Case caseObj : [Select Id from Case where Id in :Trigger.newMap.keySet()])
            {
                Database.DMLOptions dmoObj = new Database.DMLOptions();
                dmoObj.assignmentRuleHeader.assignmentRuleId= arRuleList[0].id;                    
                caseObj.setOptions(dmoObj);
                caseList.add(caseObj);
            }
            
            Update caseList;   
        }
    }
}

In same way you can create a trigger on Lead object to set default assignment rule to new created Lead.

How To Create Lightning Component?

Before start learning about Lightning Component you have to know about Apex Class, Javascript & HML also OOPs Concept.  After reading this article you will be able to create, extends and implements Lightning Components. Here you also learn about lightning method  in lightning component.
Note: You must registered a domain under My Domain. To register your domain Click Here

Let’s create a component named HelloWorld.

Step 1: Go-to Developer Console–> Files–> New–>Lightning Component

Create New Lightning Component

Enter Component Name HelloWorld and click on Submit Button. Lightning component root tag is <aura:component ></aura:component>.

Step 2 Let’s create attribute

<aura:component>

<aura:attribute name=”fullname” type=”String” default=”Your Name” description=”User full name”/>

<aura:attribute name=”email” type=”String” default=”” description=”User email address”/>

</aura:component>

We have created two attribute fullname and email while defined attribute name follow variable naming rule.

Do not use space in attribute name like name=”full name” this is Wrong, it should be like above attribute name.

Step 3 How to get attribute value in component?

This is very simple {!v.attributename}, if you want to get fullname and email attributes value then you should write {!v.fullname} and {!v.email}.

Step 4 Let’s create a lightning button and bind with component controller

<aura:component>

<aura:attribute name=”fullname” type=”String” default=”Your Name” description=”User full name”/>

<aura:attribute name=”email” type=”String” default=”” description=”User email address”/>

<lightning:button onclick=”{!c.alertName}” label=”Alert Name”/>

</aura:component>

To bind controller action with lightning button we use {!c.actionName}

Lightning Component Controller

HelloWorldController.js

({
      //Action alertName 
      alertName : function(component, event, helper) {
	  alert(component.get("v.fullName"));
          //Using component getting attribute value here same as in component.
      },
      // you can write another action here
      //parameter name can be change
      action2: function(com,ev,help){
          //getting attibute value here
          com.get("v.attributename");
      }
})

<h2> Test your created component</h2>

Now Create a lightning App in same way as you follow previous steps. Go to developer console -> file -> new -> Lightning Application. Enter DemoApp in App name and click submit button.

<aura:application exends=”force:slds”>
<c:HelloWorld/>
</aura:application>

Note: Use Ctr+S to save component or any file in developer console. click on preview button to see result of your create component. Here we used exends=”force:slds” in app that means by default salesforce lightning design system apply in your app.

 

 

How to create multi-picklist in salesforce lightning component

Multi picklist in salesforce lightning component.
There are only four steps to create mullti picklist in salesforce ligthning component.

multi picklist in salesforce lightning component

Step – 1

let’s create a lightning component named “demoMultipicklistCmp.cmp

<aura:component>
<aura:attribute name=”options” type=”list” default=”[]”/>
<aura:attribute name=”selectedOptions” type=”String” default=””/>
<aura:handler name=”init” value=”{!this}” action=”{!c.doInit}”/>
<div class=”slds-form-element”>
<label class=”slds-form-element__label” for=”combobox-unique-id-3″>Search</label>
<div class=”slds-form-element__control”>
<div class=”slds-combobox_container slds-size_small”><!–slds-is-open–>
<div aura:id=”dropdown” onmouseenter=”{!c.openDropdown}” onmouseleave=”{!c.closeDropDown}”    class=”slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click slds-is-close” aria-expanded=”true” aria-haspopup=”listbox” role=”combobox”>
<div class=”slds-combobox__form-element slds-input-has-icon slds-input-has-icon_right” role=”none”>
<input type=”text” class=”slds-input slds-combobox__input slds-combobox__input-value”
placeholder=”Select an Option” readonly=”true” onfocus=”{!c.openDropdown}” value=”{!v.selectedOptions}”/>
<span class=”slds-icon_container slds-icon-utility-down slds-input__icon slds-input__icon_right” title=”Down icon”>
<lightning:icon iconName=”utility:down” size=”xx-small” class=”slds-icon-text-default”/>
<span class=”slds-assistive-text”>Down icon</span>
</span>
</div>
<div id=”listbox-unique-id” role=”listbox”>
<ul class=”slds-listbox slds-listbox_vertical slds-dropdown slds-dropdown_fluid” role=”presentation”>
<aura:iteration items=”{!v.options}” var=”item” indexVar=”ind”>
<li onclick=”{!c.selectOption}” id=”{!item.label+’#BP#’+item.isChecked}” role=”presentation” class=”slds-listbox__item”><!–slds-is-selected–>
<div id=”{!’listbox-option-unique-id-‘+(ind+1)}”
class=”{!item.isChecked==true?’slds-media slds-listbox__option slds-listbox__option_plain slds-media_small slds-media_center slds-is-selected’:’slds-media slds-listbox__option slds-listbox__option_plain slds-media_small slds-media_center ‘}” role=”option”>
<span class=”slds-media__figure”>
<lightning:icon iconName=”utility:check” size=”xx-small” class=”slds-listbox__icon-selected”/>
</span>
<span class=”slds-media__body”>
<span class=”slds-truncate” title=”{!item.label}”> {!item.label}</span>
</span>
</div>
</li>
</aura:iteration>
</ul>
</div>
</div>
</div>
</div>
</div>
</aura:component>

Step-2
Javascript Controller Named “demoMultipicklistCmpController.cmp
Use following code to handle open, close and handle dropdown option selection.

({
    doInit:function(component,event,helper){
        var opt =[];
        for(var i=1;i<=5;i++){
            if(i==1){
             	opt.push({label:'Items '+i,isChecked:true});
            }
            else{
             	opt.push({label:'Items '+i,isChecked:false});   
            }
        }
        component.set("v.options",opt);
        helper.selectOptionHelper(component,'Item 1','true');       
    },
    openDropdown:function(component,event,helper){
        $A.util.addClass(component.find('dropdown'),'slds-is-open');
        $A.util.removeClass(component.find('dropdown'),'slds-is-close');
    },
    closeDropDown:function(component,event,helper){
        $A.util.addClass(component.find('dropdown'),'slds-is-close');
        $A.util.removeClass(component.find('dropdown'),'slds-is-open');
    },
    selectOption:function(component,event,helper){        
        var label = event.currentTarget.id.split("#BP#")[0];
        var isCheck = event.currentTarget.id.split("#BP#")[1];
        helper.selectOptionHelper(component,label,isCheck);
    }
})

Step-3
Require a helper named “demoMultipicklistCmpHelper.cmp” to handle dropdown selection

({
    selectOptionHelper : function(component,label,isCheck) {
        var selectedOption='';
		var allOptions = component.get('v.options');
        var count=0;
        for(var i=0;i<allOptions.length;i++){ if(allOptions[i].label==label) { if(isCheck=='true'){ allOptions[i].isChecked = false; }else{ allOptions[i].isChecked = true; } } if(allOptions[i].isChecked){ selectedOption=allOptions[i].label; count++; } } if(count>1){
            selectedOption = count+' items selected';
        }
        component.set("v.selectedOptions",selectedOption);
        component.set('v.options',allOptions);
    }
})

Step-4
Your component is created now you are able to use component in lightning app to test your component. Let’s create a lightning app named “demoMultipicklistApp.app“. app code will be

<aura:application extends=”force:slds”>
<c:demoMultipicklistCmp/>
</aura:application>

In app we are using Salesforce Lightning Design System by extending force:slds

HOw to set options of multi picklist in salesforce lightning component using apex controller

You can set options attribute from apex controller. Create a apex class “Demo_Controller”

public class Demo_Controller{
    @AuraEnabled
    public static List getOptions()
    {
        List optList = new List();
		
	optList.add(new PickListOptions('Option 1',false));
	optList.add(new PickListOptions('Option 2',true));
	optList.add(new PickListOptions('Option 3',false));
	return optList;
    }

	// wrapper class 
	public class PickListOptions
	{
		@AuraEnabled public String label;
		@AuraEnabled public boolean isChecked;
		public PickListOptions(String label,boolean isChecked){
			this.label = label;
			this.isChecked = isChecked;
		}
	}
}

Here using @AuraEnabled annotation that means method become available in lightning. Now update your helper and create a new helper method

getOpetionsHelper: function(component)
{
      	var action = component.get("c.getOptions");
	// set if using parameter in your apex controller action 
	//action.setParams({ paramName : 'paramvalue' });

	// Create a callback that is executed after        
	action.setCallback(this, function(response) {
		var state  = response.getState(); // return SUCCESS,INCOMPLETE or ERROR string
		var result = response.getReturnValue(); // list return by @AuraEnabled getOptions action 
		
		for(var i=0;i<=result.length;i++){            
			opt.push({label:result[i].label,isChecked:result[i].isChecked});
        }
        component.set("v.options",opt);
	});
	
	// $A.enqueueAction adds the server-side action to the queue.
	$A.enqueueAction(action);

} 

Note: your helper and JS controller method name must not equal to @AuraEnabled apex controller action name.