Tag Archives: Lightning Component

Lightning Component to Open URL in Browser New Tab on Button Click

Lightning Component:

<!--Sample.cmp-->
<aura:component implements="flexipage:availableForAllPageTypes, force:appHostable" access="global">
    <aura:attribute name="recordId" type="string" default="0019000001DEV5z"/>
    
    <div class="slds-m-around--xx-large">
        <!--Open URL in New Browser Tab-->
        <lightning:button label="Open in New Window" variant="brand" onclick="{!c.handleOpenInNewWindow}"/>
        <!--Open URL in New Browser Tab With Record Id-->
        <lightning:button label="Open in New Window With RecordId" variant="brand" onclick="{!c.handleOpenNewWindowWithRecordId}"/>
    </div>
</aura:component>

Lightning JS Controller:

({
    //Open URL in New Browser Tab
    handleOpenInNewWindow : function(component, event, helper) {
        window.open("https://www.salesforce.com", '_blank');
    },
    
    //Open URL in New Browser Tab With Record Id
    handleOpenNewWindowWithRecordId : function(component, event, helper) {
        var recordId = component.get('v.recordId');
        window.open('/' + recordId,'_blank');
    }
})

Custom Label in Lightning Component

Custom Label in Lightning Component:
$Label.c.labelName for the default namespace.
$Label.namespace.labelName if your org has a namespace, or to access a label in a managed package.

<aura:component implements="flexipage:availableForAllPageTypes">
    <div onclick="{!c.clickLabel}">
        <ui:outputText value="{!$Label.c.Message}" />
    </div>
</aura:component>

Custom Label in Javascript:
$A.get(“$Label.c.labelName”) for the default namespace.
$A.get(“$Label.namespace.labelName”) if your org has a namespace, or to access a label in a managed package.

({
    clickLabel : function(component, event, helper) {
        var label = $A.get("$Label.c.Message");
        alert(label);
    }
})

Get Picklist Values Dynamically In Lightning Component

In below example I’m retrieving “Account” object “Industry” picklist values and populating on lightning component using lightning:select and creating account record.

Apex Controller:

public class SampleAuraController {
    
    @AuraEnabled //Save Account Data
    Public static void createAccount(Account objacc){
        try{
            //Insert Account Record
            insert objacc; 
            
        }catch(Exception e){
            //throw exception message
            throw new AuraHandledException(e.getMessage());
        }
        finally {
        }
    }
    
    @AuraEnabled //get Account Industry Picklist Values
    public static Map<String, String> getIndustry(){
        Map<String, String> options = new Map<String, String>();
        //get Account Industry Field Describe
        Schema.DescribeFieldResult fieldResult = Account.Industry.getDescribe();
        //get Account Industry Picklist Values
        List<Schema.PicklistEntry> pList = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry p: pList) {
            //Put Picklist Value & Label in Map
            options.put(p.getValue(), p.getLabel());
        }
        return options;
    }
}

Lightning Component:

<!--Sample.cmp--> 
<aura:component controller="SampleAuraController" implements="flexipage:availableForAllPageTypes,force:appHostable">
    
    <!--Declare Attributes-->
    <aura:attribute name="industryMap" type="Map"/>
    <aura:attribute name="acc" type="Account" default="{'sobjectType':'Account', 
                                                       'Name': '',
                                                       'AccountNumber': '',
                                                       'Email': '',
                                                       'Phone': '', 
                                                       'Industry': ''}"/>
    
    <!--Declare Handler-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
    
    <!--Component Start--> 
    <div class="slds-m-around--xx-large">
        <div class="container-fluid">
            <div class="form-group">
                <lightning:input name="accName" type="text" required="true" maxlength="50" label="Account Name" value="{!v.acc.Name}" />
            </div>
            <div class="form-group">
                <lightning:input name="accNumber" type="text" required="true" maxlength="10" label="Account Number" value="{!v.acc.AccountNumber}" />
            </div>
            <div class="form-group">
                <lightning:input name="accEmail" type="email" required="true" maxlength="100" label="Email" value="{!v.acc.Email}" />
            </div>
            <div class="form-group">
                <lightning:input name="accPhone" type="phone" required="true" maxlength="10" label="Phone" value="{!v.acc.Phone}" />
            </div>
            <div class="form-group">
                <lightning:select aura:id="industryPicklist" value="{!v.acc.Industry}" onchange="{!c.handleCompanyOnChange}" name="industryPicklist" label="Industry" required="true">
                    <option value="">--None--</option>
                    <aura:iteration items="{!v.industryMap}" var="ind" indexVar="key">
                        <option text="{!ind.value}" value="{!ind.key}" selected="{!ind.key==v.acc.Industry}" />
                    </aura:iteration>
                </lightning:select>
            </div>
        </div>
        <br/>
        <lightning:button variant="brand" label="Submit" onclick="{!c.handleAccountSave}" />              
    </div>
    <!--Component End-->
</aura:component>

Lightning JS Controller:

({
    //Load Account Industry Picklist
    doInit: function(component, event, helper) {        
        helper.getIndustryPicklist(component, event);
    },
    
    //handle Account Save
    handleAccountSave : function(component, event, helper) {
        helper.saveAccount(component, event);
    },
    
    //handle Industry Picklist Selection
    handleCompanyOnChange : function(component, event, helper) {
        var indutry = component.get("v.acc.Industry");
        alert(indutry);
    }
})

Lightning JS Helper:

({
    //get Industry Picklist Value
    getIndustryPicklist: function(component, event) {
        var action = component.get("c.getIndustry");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                var industryMap = [];
                for(var key in result){
                    industryMap.push({key: key, value: result[key]});
                }
                component.set("v.industryMap", industryMap);
            }
        });
        $A.enqueueAction(action);
    },
    
    //handle Account Save
    saveAccount : function(component, event) {
        var acc = component.get("v.acc");
        var action = component.get("c.createAccount");
        action.setParams({
            objacc : acc
        });
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                alert('Record is Created Successfully');
            } else if(state === "ERROR"){
                var errors = action.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert(errors[0].message);
                    }
                }
            }else if (status === "INCOMPLETE") {
                alert('No response from server or client is offline.');
            }
        });       
        $A.enqueueAction(action);
    }
})

Output:

Set or Modify Field Values in Onsubmit Event of lightning:recordeditform

Sometimes we can have a requirement to add or modify field values in onsubmit event of lightning:recordeditform. In below example, I’m creating “Lead” object record using lightning:recordeditform and in onsubmit event, I’m adding “Description” field value of “Lead” object.

Lightning Component:

<!--Sample.cmp--> 
<aura:component implements="flexipage:availableForAllPageTypes,force:appHostable">
    
    <!--Component--> 
    <div class="slds-m-around--xx-large">
        <lightning:card title="Lead" iconName="standard:lead" class="slds-p-around_medium">
            <lightning:recordEditForm aura:id="leadCreateForm" objectApiName="Lead" onsubmit="{!c.handleOnSubmit}">
                <lightning:messages />
                
                <div class="slds-grid">
                    <div class="slds-col slds-size_1-of-2 slds-p-around_medium">
                        <lightning:inputField fieldName="FirstName"></lightning:inputField>
                    </div>
                    <div class="slds-col slds-size_1-of-2 slds-p-around_medium">
                        <lightning:inputField fieldName="LastName"></lightning:inputField>
                    </div>
                </div>
                
                <div class="slds-grid">
                    <div class="slds-col slds-size_1-of-2 slds-p-around_medium">
                        <lightning:inputField fieldName="Email"></lightning:inputField>
                    </div>
                    <div class="slds-col slds-size_1-of-2 slds-p-around_medium">
                        <lightning:inputField fieldName="Phone"></lightning:inputField>
                    </div>
                </div>
                
                <div class="slds-grid">
                    <div class="slds-col slds-size_1-of-2 slds-p-around_medium">
                        <lightning:inputField fieldName="Company"></lightning:inputField>
                    </div>
                </div>
                
                <lightning:button type="submit" label="Save" variant="brand"/>
            </lightning:recordEditForm>
        </lightning:card>
    </div>
</aura:component>

Lightning JS Controller:

({
    handleOnSubmit : function(component, event, helper) {
        event.preventDefault(); //Prevent default submit
        var eventFields = event.getParam("fields"); //get the fields
        eventFields["Description"] = 'Lead was created from Lightning RecordEditForm'; //Add Description field Value
        component.find('leadCreateForm').submit(eventFields); //Submit Form
    }
})

Get lightning:recordeditform Field Values in onsuccess Event

Sometimes we can have a requirement to get field values, record Id, record type Id, child relationships information in onsuccess event of lightning:recordeditform. In below example, I’m creating “Lead” object record using lightning:recordeditform and after successfully saving the record, getting the field values in onsuccess event.

Lightning Component:

<!--Sample.cmp--> 
<aura:component implements="flexipage:availableForAllPageTypes,force:appHostable">
    
    <!--Component--> 
    <div class="slds-m-around--xx-large">
        <lightning:card title="Lead" iconName="standard:lead" class="slds-p-around_medium">
            <lightning:recordEditForm aura:id="leadCreateForm" objectApiName="Lead" onsuccess="{!c.handleOnSuccess}">
                <lightning:messages />
                
                <div class="slds-grid">
                    <div class="slds-col slds-size_1-of-2 slds-p-around_medium">
                        <lightning:inputField fieldName="FirstName"></lightning:inputField>
                    </div>
                    <div class="slds-col slds-size_1-of-2 slds-p-around_medium">
                        <lightning:inputField fieldName="LastName"></lightning:inputField>
                    </div>
                </div>
                
                <div class="slds-grid">
                    <div class="slds-col slds-size_1-of-2 slds-p-around_medium">
                        <lightning:inputField fieldName="Email"></lightning:inputField>
                    </div>
                    <div class="slds-col slds-size_1-of-2 slds-p-around_medium">
                        <lightning:inputField fieldName="Phone"></lightning:inputField>
                    </div>
                </div>
                
                <div class="slds-grid">
                    <div class="slds-col slds-size_1-of-2 slds-p-around_medium">
                        <lightning:inputField fieldName="Company"></lightning:inputField>
                    </div>
                </div>
                
                <lightning:button type="submit" label="Save" variant="brand"/>
            </lightning:recordEditForm>
        </lightning:card>
    </div>
</aura:component>

Lightning JS Controller:

({
    handleOnSuccess : function(component, event, helper) {
        var param = event.getParams(); //get event params
        var fields = param.response.fields; //get all field info
        var childRelationships = param.response.childRelationships; //get child relationship info
        var recordTypeInfo = param.response.recordTypeInfo; //get record type info
        var recordId = param.response.id; //get record id
        
        console.log('Param - ' + JSON.stringify(param)); 
        console.log('Fields - ' + JSON.stringify(fields)); 
        console.log('Child Relationship - ' + JSON.stringify(childRelationships)); 
        console.log('Record Type Info - ' + JSON.stringify(recordTypeInfo)); 
        console.log('Record Id - ' + JSON.stringify(recordId)); 
        
        //get Record Edit Form Field Values
        console.log('FirstName - ' + fields.FirstName.value);
        console.log('LastName - ' + fields.LastName.value);
        console.log('Email - ' + fields.Email.value);
        console.log('Phone - ' + fields.Phone.value);
        console.log('Company - ' + fields.Company.value);
    }
})