Tag Archives: Lightning Component

Get Picklist Values on a Lightning Component

In below example I’m retrieving “Account” object “Industry” picklist values and populating on lightning component using ui:inputSelect.

Apex Class:

public class AccountAuraController {
    @AuraEnabled
    public static List<String> getIndustry(){
        List<String> options = new List<String>();
        Schema.DescribeFieldResult fieldResult = Account.Industry.getDescribe();
        List<Schema.PicklistEntry> pList = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry p: pList) {
            options.add(p.getLabel());
        }
        return options;
    }
}

Component:

<!--TestComponent-->
<aura:component controller="AccountAuraController" access="global" implements="force:appHostable">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>    
    <div class="slds-form-element">
        <label class="slds-form-element__label" for="select-01">Select Industry</label>
        <div class="slds-select_container">
            <ui:inputSelect label="Industry" class="dynamic" aura:id="InputAccountIndustry" change="{!c.onPicklistChange}"/> 
        </div>
    </div>
</aura:component>

Component Controller:

({
    doInit: function(component, event, helper) {
        var action = component.get("c.getIndustry");
        var inputIndustry = component.find("InputAccountIndustry");
        var opts=[];
        action.setCallback(this, function(a) {
            opts.push({
                class: "optionClass",
                label: "--- None ---",
                value: ""
            });
            for(var i=0;i< a.getReturnValue().length;i++){
                opts.push({"class": "optionClass", label: a.getReturnValue()[i], value: a.getReturnValue()[i]});
            }
            inputIndustry.set("v.options", opts);
            
        });
        $A.enqueueAction(action); 
    },
    onPicklistChange: function(component, event, helper) {
        //get the value of select option
        var selectedIndustry = component.find("InputAccountIndustry");
        alert(selectedIndustry.get("v.value"));
    },
})

Lightning App:

<!--TestApp-->
<aura:application extends="ltng:outApp" access="global">
    <c:TestComponent />
</aura:application>

Output:

Salesforce Lightning Value Providers

Value providers are a way to access data. Value providers encapsulate related values together, similar to how an object encapsulates properties and methods. The value providers for a component are v (view) and c (controller).

v (View) Value Provider: This value provider enables you to access the value of a component’s attribute in the component’s markup.

Component:

In below component the name of the attribute is defined as “whom” String, If no value is specified, it defaults to “World”. Where “v” is the value provider for a component attribute which represent the view.

<aura:application>
    <aura:attribute name="whom" type="String" default="World"/>
    Hello {!v.whom}!
</aura:application>

c (Controller) Value Provider: This value provider enables you to wire up event handlers and action for the component. Client side controller handles events within a component. It’s a JavaScript resource that defined the functions for all of the components actions.

Component:
In below component the name of the attribute is defined as “text” String, If no value is specified, it defaults to “Just a string” and “v” is the value provider for a component attribute which represent the view. The Lightning framework button wires the onclick attribute in the lightning:button component to the handleClick action in the controller.

<aura:component>
    <aura:attribute name="text" type="String" default="Just a string."/>
    <lightning:button label="Framework Button" onclick="{!c.handleClick}"/>
    
    {!v.text}
</aura:component>

Component Controller:
A client-side controller handles events within a component. It’s a JavaScript resource that defines the functions for all of the component’s actions.

The controller is a JavaScript object in object-literal notation containing a map of name-value pairs. Each name corresponds to a client-side action. Its value is the function code associated with the action. Client-side controllers are surrounded by parentheses and curly braces. Separate action handlers with commas (as you would with any JavaScript map).

In the below Component Controller handleClick function, notice that the first argument to every action is the component to which the controller belongs. One of the most common things you’ll want to do with this component is look at and change its attribute values.

cmp.get("v.attributeName") returns the value of the attributeName attribute.

cmp.set("v.attributeName", "attribute value") sets the value of the attributeName attribute.

({
    handleClick : function(cmp, event, helper) {
        var attributeValue = cmp.get("v.text");
        console.log("String Value: " + attributeValue);
        var changeStringValue = 'Change the string value';
        cmp.set("v.text", changeStringValue);
    }
})

Each action function takes in three parameters:

cmp — The component to which the controller belongs.
event — The event that the action is handling.
helper — The component’s helper, which is optional. A helper contains functions that can be reused by any JavaScript code in the component bundle.

Set Default Value in Picklist in Lightning Component

Here in below example the default value in picklist is “Apple”.
Lightning Component:

<aura:component>
    <ui:inputSelect aura:Id="brandId" multiple="false" label="Select Brand">
        <ui:inputSelectOption label="Apple" text="Apple" value="true"/>
        <ui:inputSelectOption label="Nokia" text="Nokia"/>
        <ui:inputSelectOption label="Samsung" text="Samsung"/>
        <ui:inputSelectOption label="Google" text="Google"/>
        <ui:inputSelectOption label="Mi" text="Mi"/>
    </ui:inputSelect>
</aura:component>

Output:

Dynamic Add Delete Row In Lightning Component

In below example I’m adding account record in Salesforce Lightning Component with Add Delete Rows functionality.

Apex Class:

public with sharing class AuraSampleController{
    
    @AuraEnabled
    public static void saveAccounts(List<Account> accList){
        Insert accList;
    }
}

Lightning Component:

<aura:component controller="AuraSampleController" Implements="flexipage:availableForRecordHome,force:hasRecordId">
    
    <aura:attribute name="accountList" type="Account[]"/> 
    
    <div class="slds-m-around--xx-large">
        <div class="slds-float_right slds-p-bottom_small">
            <h1 class="slds-page-header__title">Add Row 
                <lightning:buttonIcon iconName="utility:add"  size="large" variant="bare" alternativeText="Add" onclick="{!c.addRow}"/>
            </h1>
        </div>
        <div class="container-fluid">        
            <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
                <thead>
                    <tr class="slds-text-title_caps">
                        <th scope="col">
                            <div class="slds-truncate">#</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Account Name">Account Name</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Account Number">Account Number</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Phone">Phone</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Action">Action</div>
                        </th>
                    </tr>
                </thead>   
                <tbody>      
                    <aura:iteration items="{!v.accountList}" var="acc" indexVar="index">
                        <tr>
                            <td> 
                                {!index + 1}
                            </td>
                            <td>
                                <lightning:input name="accName" type="text" required="true" maxlength="50" label="Account Name" value="{!acc.Name}" />
                            </td>
                            <td>
                                <lightning:input name="accNumber" type="text"  maxlength="10" label="Account Number" value="{!acc.AccountNumber}" />
                            </td>
                            <td>
                                <lightning:input name="accPhone" type="phone" maxlength="10" label="Phone" value="{!acc.Phone}" />
                            </td>
                            <td>
                                <a onclick="{!c.removeRow}" data-record="{!index}">
                                    <lightning:icon iconName="utility:delete" size="small" alternativeText="Delete"/>
                                    <span class="slds-assistive-text">Delete</span>
                                </a>
                            </td> 
                        </tr>
                    </aura:iteration>
                </tbody>
            </table>
            <div class="slds-align_absolute-center slds-p-top_small">
                <lightning:button variant="brand" label="Submit" title="Brand action" onclick="{!c.save}" />
            </div>
        </div>
    </div>
</aura:component>

Lightning JS Controller:

({
    addRow: function(component, event, helper) {
        helper.addAccountRecord(component, event);
    },
    
    removeRow: function(component, event, helper) {
        //Get the account list
        var accountList = component.get("v.accountList");
        //Get the target object
        var selectedItem = event.currentTarget;
        //Get the selected item index
        var index = selectedItem.dataset.record;
        accountList.splice(index, 1);
        component.set("v.accountList", accountList);
    },
    
    save: function(component, event, helper) {
        if (helper.validateAccountList(component, event)) {
            helper.saveAccountList(component, event);
        }
    },
})

Lightning JS Helper:

({
    addAccountRecord: function(component, event) {
        //get the account List from component  
        var accountList = component.get("v.accountList");
        //Add New Account Record
        accountList.push({
            'sobjectType': 'Account',
            'Name': '',
            'AccountNumber': '',
            'Phone': ''
        });
        component.set("v.accountList", accountList);
    },
    
    validateAccountList: function(component, event) {
        //Validate all account records
        var isValid = true;
        var accountList = component.get("v.accountList");
        for (var i = 0; i < accountList.length; i++) {
            if (accountList[i].Name == '') {
                isValid = false;
                alert('Account Name cannot be blank on row number ' + (i + 1));
            }
        }
        return isValid;
    },
    
    saveAccountList: function(component, event, helper) {
        //Call Apex class and pass account list parameters
        var action = component.get("c.saveAccounts");
        action.setParams({
            "accList": component.get("v.accountList")
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.accountList", []);
                alert('Account records saved successfully');
            }
        }); 
        $A.enqueueAction(action);
    },
})

Create Account Record :

Created Account Records :

Multiple Conditions in aura:if on Lightning Component

aura:if evaluates the isTrue expression on the server and instantiates components in either its body or else attribute. Only one branch is created and rendered. Switching condition unrenders and destroys the current branch and generates the other.

In aura:if tag we can not use &&,AND,||,OR operator for multiple conditions in isTrue attribute, but we can use logical functions in aura:if tag like or(), and().

Here is the example how to use multiple Boolean conditions in aura:if tag.

Lightning Component:

<!--Sample.cmp--> 
<aura:component implements="flexipage:availableForAllPageTypes,force:appHostable">
    
    <!--Declare Attributes-->
    <aura:attribute name="attribute1" type="boolean" default="true"/>
    <aura:attribute name="attribute2" type="boolean" default="false"/>
    <aura:attribute name="attribute3" type="boolean" default="true"/>
    <aura:attribute name="attribute4" type="boolean" default="false"/>
    
    <!--Component Start--> 
    <div class="slds-m-around--xx-large">
        <!--aura:if with and condition-->
        <aura:if  isTrue="{!and(v.attribute1, v.attribute3)}" >
            <p><strong>Both attributes are true</strong></p>
        </aura:if>
        <!--aura:if with aura:set-->
        <aura:if  isTrue="{!or(v.attribute4, v.attribute2)}">
            <p><strong>Only One attribute is true</strong></p>
            <aura:set attribute="else">
                <p><strong>Both attributes are false</strong></p>
            </aura:set>
        </aura:if>
        <!--aura:if with nested and condition-->
        <aura:if  isTrue="{!or(and(v.attribute1, v.attribute3), v.attribute2)}" >
            <p><strong>One of or condition returns true</strong></p>
        </aura:if>
    </div>
    <!--Component End-->
</aura:component>

Output: