Tag Archives: Lightning Component

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:

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:

<!--TestComponent-->
<aura:component >
    <aura:attribute name="ATrue" type="boolean" default="true"/>
    <aura:attribute name="BFalse" type="boolean" default="false"/>
    <aura:attribute name="CTrue" type="boolean" default="true"/>
    <aura:attribute name="DFalse" type="boolean" default="false"/>
    
    <!--aura:if Sample -->
    <aura:if  isTrue="{!and(v.ATrue, v.CTrue)}" >
        <div style="padding:15px; background-color:LightBlue">
            And => This div show because both A and C attributes are true
        </div>
    </aura:if>
    <!--aura:if with aura:set sample-->
    <aura:if  isTrue="{!or(v.DFalse, v.BFalse)}">
        <div style="padding:15px;">
            Or => This div show because one attribute is true
        </div>
        <aura:set attribute="else">
            <div style="padding:15px;">
                Or => This div show because both attributes are false
            </div>
        </aura:set>
    </aura:if>
    <!--aura:if with nested and condition-->
    <aura:if  isTrue="{!or(and(v.ATrue, v.CTrue), v.BFalse)}" >
        <div style="padding:15px; background-color:LightGreen  ">
            Nested condition div show because in statment one of or condition returns true
        </div>
    </aura:if>
</aura:component>

Lightning App:

<!--TestApp-->
<aura:application>
    <c:TestComponent/>
</aura:application>

Output:

Use Lightning Component in Visualforce Page

In Winter’16 the ability to add Lightning Components to Visualforce pages was made generally available. This powerful new feature allows you to reuse existing Lightning Components or design and implement new features as Lightning Components with the flexibility to use of them in new or existing Visualforce pages.

This article is to show you how to add Lightning components to Visualforce pages.

Let’s create a lightning component named “HelloWorld.cmp” either through developer console or through your IDE. Use the below mentioned code in your lightning component.

Lightning Component:

<!--HelloWorld-->
<aura:component implements="force:appHostable">
    <div>
        Hello World    
    </div>
</aura:component>

Now we use this Lightning component in a Lightning app. For this I recommend you to create a new Lightning app, let’s call it “HelloWorldApp.app” and use the above lightning component “HelloWorld.cmp” in this app.

Lightning App:

<!--HelloWorldApp-->
<aura:application extends="ltng:outApp" access="global">
    <aura:dependency resource="c:HelloWorld"/>
</aura:application>

In above Lightning app, I have used aura application access as global, so that it can be used anywhere in Salesforce organization like Visualforce. Extending ltng:outApp indicates that any component defined in this application can be used on Visualforce page.

Now create a VisualForce page which would display this lightning component. VisualForce page would provide the interface where we can view the lightning component that we are going to use in the page. Use the below code in your VF page.

In my Visualforce page, we have a special include apex:includeLightning for Lighting. We also need to create a container div id="LightningContainer" for the Lightning components to appear in.

Visualforce Page:

<apex:page >
    <apex:includeLightning />
    <div style="width:100%;height:100px;" id="LightningContainer" />
    
    <script>
        $Lightning.use("c:HelloWorldApp", function() {
            $Lightning.createComponent("c:HelloWorld", { },
            "LightningContainer",
            function(cmp) {
                console.log('Component created');
            });
        });
    </script>
</apex:page>

Note: If your Org has a namespace, then in Visualforce page we have to mention the namespace for Lightning app as yournamespace:HelloWorldApp instead of c:HelloWorldApp.

Here is the Visualforce page output:

Call Multiple Apex Methods in Lightning Controller

Apex Controller:

public with sharing class AccountController {

    @AuraEnabled
    public static Account getAccount(Id accountId) {
        Account acc = new Account();
        acc = [SELECT Id, Name, Description FROM Account WHERE Id=:accountId];
        return acc;
    }
    
    @AuraEnabled
    public static List<Attachment> getAttachments(Id parentId) {                            
        List<Attachment> listAttachment = new List<Attachment>();
        listAttachment = [SELECT Id, Name FROM Attachment WHERE ParentId = :parentId];
        return listAttachment;
    }
}

Lightning Component:

<aura:component controller="AccountController" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" access="global">
    <aura:attribute name="recordId" type="Id" />
    <aura:attribute name="acc" type="Account"/>
    <aura:attribute name="attachments" type="Attachment[]"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <div>
        <div>{!v.acc.Name}</div>
        <div>{!v.acc.Description}</div>
        
        <ul>
            <aura:iteration items="{!v.attachments}" var="a">
                <li>
                    <a target="_blank" href="{! '/servlet/servlet.FileDownload?file=' + a.Id }">{!a.Name}</a>
                </li>
            </aura:iteration>
        </ul>
    </div>

Lightning Controller:

({
    doInit : function (component) {
    var action = component.get('c.getAccount');
    action.setParams({
        "accountId": component.get("v.recordId")
    });
        
	action.setCallback(this, function(response) {
        var state = response.getState();
        if (state == "SUCCESS") {
            var account = response.getReturnValue();
            component.set("v.acc", account);
        }
    });
        
    var action2 = component.get('c.getAttachments');
    action2.setParams({
        "parentId": component.get("v.recordId")
    });
        
	action2.setCallback(this, function(response) {
        var state = response.getState();
        if (state == "SUCCESS") {
            var attachments = response.getReturnValue();
            component.set("v.attachments", attachments);
        }
    });
    $A.enqueueAction(action);
    $A.enqueueAction(action2);
}
})