Category Archives: JavaScript

Navigate From One Lightning Component to Another Lightning Component

Component1:

<!--Component1-->
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" >
    <div>
        Component 1   
    </div>     
    <lightning:button variant="brand" label="Navigate to Component 2" onclick="{!c.navigate}" /> 
</aura:component>

Component1 Controller:

({
    navigate : function(component, event, helper) {
        var navigateEvent = $A.get("e.force:navigateToComponent");
        navigateEvent.setParams({
            componentDef: "c:Component2"
            //You can pass attribute value from Component1 to Component2
            //componentAttributes :{ }
        });
        navigateEvent.fire();
    }
})

Component2:

<!--Component2-->
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" >
    <div>   
        Component 2
    </div>    
    <lightning:button variant="brand" label="Navigate to Component 1" onclick="{!c.navigate}" />
</aura:component>

Component2 Controller:

({
    navigate : function(component, event, helper) {
        var navigateEvent = $A.get("e.force:navigateToComponent");
        navigateEvent.setParams({
            componentDef: "c:Component1"
            //You can pass attribute value from Component2 to Component1
            //componentAttributes :{ }
        });
        navigateEvent.fire();
    }
})

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 :

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);
}
})

Copy Billing Address to Shipping Address in Salesforce Visualforce Page

<apex:page standardController="Contact" extensions="ContactExtn" id="pgContact">

    <script type="text/javascript">
        function copyAddress() {
            // Variables for Billing Address
            var copy_BillingPostalCode = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBPostalCode').value;
            var copy_BillingAddress1 =document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBAdd1').value;
            var copy_BillingAddress2 = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBAdd2').value;
            var copy_BillingAddress3 = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBAdd3').value;
            var copy_BillingCity = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBCity').value;
            var copy_BillingState = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBState').value;
            var copy_BillingCountry = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBCountry').value;
           
            // Copying the Billing Address to the Shipping Address
            if(copy_BillingPostalCode != null)
            {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSPostalCode').value = copy_BillingPostalCode;
             }
            if(copy_BillingAddress1 != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSAdd1').value = copy_BillingAddress1;
            }
            if(copy_BillingAddress2 != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSAdd2').value = copy_BillingAddress2;
            }
            if(copy_BillingAddress3 != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSAdd3').value = copy_BillingAddress3;
            }
            if(copy_BillingCity != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSCity').value = copy_BillingCity;
            }
            if(copy_BillingState != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSState').value = copy_BillingState;
            }
            if(copy_BillingCountry != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSCountry').value = copy_BillingCountry;
            }
        }
    </script>
        
    <apex:form id="fmContact">
        <apex:sectionHeader title="Contact Information" subtitle="{!Contact.Name}"/>
        <apex:pageBlock mode="Edit" id="pbContact">
            <apex:pageBlockSection showHeader="true" collapsible="false" columns="2" title="Billing Address Information" id="pbsBillingAdd">
                <apex:inputField value="{!Contact.Billing_Postal_Code__c}" id="ifBPostalCode"/>
                <apex:inputField value="{!Contact.Billing_City__c}" id="ifBCity"/>
                <apex:inputField value="{!Contact.Billing_Address_Line_1__c}" id="ifBAdd1"/>
                <apex:inputField value="{!Contact.Billing_State__c}" id="ifBState"/>
                <apex:inputField value="{!Contact.Billing_Address_Line_2__c}" id="ifBAdd2"/>
                <apex:inputField value="{!Contact.Billing_Country__c}" id="ifBCountry"/>
                <apex:inputField value="{!Contact.Billing_Address_Line_3__c}" id="ifBAdd3"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection showHeader="true" collapsible="false" columns="2" title="Shipping Address Information" id="pbsShippingAdd">
                <apex:inputField value="{!Contact.Shipping_Postal_Code__c}" id="ifSPostalCode"/>
                <a HREF="#" onClick="return copyAddress();">Copy Billing Address to Shipping Address</a>
                <apex:inputField value="{!Contact.Shipping_Address_Line_1__c}" id="ifSAdd1"/>
                <apex:inputField value="{!Contact.Shipping_City__c}" id="ifSCity"/>
                <apex:inputField value="{!Contact.Shipping_Address_Line_2__c}" id="ifSAdd2"/>
                <apex:inputField value="{!Contact.Shipping_State__c}" id="ifSState"/>
                <apex:inputField value="{!Contact.Shipping_Address_Line_3__c}" id="ifSAdd3"/>
                <apex:inputField value="{!Contact.Shipping_Country__c}" id="ifSCountry"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Custom Send Email Button on Custom Objects

  • Go to Setup | Create | Objects.
  • Select your Custom Object.
  • Go to the Custom Buttons, Links and Actions section.
  • Click on New Button or Link.
  • Create a New Custom Button.
  • Select the Display Type as Detail Page Button.
  • Select the Behavior as Execute JavaScript.
  • Select the Content Source as OnClick JavaScript.
  • Include below code:
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}

window.location = '/_ui/core/email/author/EmailAuthor?rtype=003&p3_lkid={!CustomObject__c.Id}&retURL=/{!CustomObject__c.Id}&p5={!$User.Email}&p24="{!CustomObject__c.To_Email__c}&template_id=00X90000001FCj4';

Note: If the custom object holds some of the contact details then you would need to use the values from custom object, not the contact object.

Save it. Edit the Page Layout of the Custom Object and drag this button on to the Page Layout under the Custom Button section.

The information shown below are the parameters that can be added in the URL. Fields that are mark with asterisk are always needed in the URL.

Parameter Name Parameter Value
p2_lkid To (can be Contact or Lead Id)
p3_lkid Related To (usually the parent record Id)
p4 CC
p5 BCC
p6 Subject
p23 Email Body
p24 Additional To
Template_Id Salesforce email template Id
retURL Redirection page when cancel button is clicked