Day: May 29, 2018

Usage Of Lightning Navigation Event

In this blog, I am going to show how to use the different salesforce lightning navigation events. Use one of the navigation events for consistent behavior across Lightning Experience, Salesforce app, and Lightning communities.

force:navigateToComponent 

You can use this system event to  Navigates from one Lightning component to another. To navigate from a Lightning component to another, specify the component name using componentDef. This example navigates to a component c:hello and sets a value on the welcome and message attributes.

hello.cmp
<aura:component >
    <aura:attribute name ="welcome" type="String" default="welcome"/>
    <aura:attribute name ="message" type="String" default="message"/>
    Result -{!v.welcome} -{!v.message}   
</aura:component>

Here is the sample button which navigates to the lightning component on click.

    <lightning:button variant="success" label="Go to Component " title="Go to Component " onclick="{! c.navigateToMyComponent }"/>

Here is the controller action.

 navigateToMyComponent : function(component, event, helper) {
        var evt = $A.get("e.force:navigateToComponent");
        evt.setParams({
            componentDef : "c:hello",
            componentAttributes: {
                welcome : "welcome" , 
                message :"message"
            }
        });
        evt.fire();
    }
  1. The below code get the System event force:navigateToComponent
 var evt = $A.get("e.force:navigateToComponent");

2. Set the parameters like componentDef ,componentAttributes ,isredirect as shown below

 evt.setParams({
            componentDef : "c:hello",
            componentAttributes: {
                welcome : "welcome" , 
                message :"message"
            }
        });

3. fire the event

        evt.fire();

force:navigateToList

Use this event to  Navigates to the list view specified by listViewId.To navigate to a list view, set the list view ID on the listViewId attribute and fire the event. This example displays the All Opportunities list views for Opportunity on the click of the button.

        <lightning:button variant="success" label="Go to List View " title="Go to List View " onclick="{! c.gotoList }"/>

Here is the controller code

 gotoList : function (component, event, helper) {
        
        var navEvent = $A.get("e.force:navigateToList");
        navEvent.setParams({
            "listViewId": "00B6A0000059kAqUAI",
            "listViewName": null,
            "scope": "Opportunity"
        });
        navEvent.fire();
        
        
    }

force:navigateToObjectHome

Use this event to Navigates to the object home specified by the scope attribute. To navigate to an object home, set the object name on the scope attribute and fire the event. This example displays the home page for an Account object
    <lightning:button variant="success" label="Account Home" title="Account Home" onclick="{! c.navHome }"/>

controller

  navHome : function (component, event, helper) {
        var homeEvent = $A.get("e.force:navigateToObjectHome");
        homeEvent.setParams({
            "scope": "Account"
        });
        homeEvent.fire();
    }

force:navigateToRelatedList

Use this event to Navigates to the related list specified by parentRecordId.To navigate to a related list, set the parent record ID on the parentRecordId attribute and fire the event 

    <lightning:button variant="success" label="Go to RelatedList" title="Go to RelatedList" onclick="{! c.gotoRelatedList }"/>

 

  gotoRelatedList : function (component, event, helper) {
        var relatedListEvent = $A.get("e.force:navigateToRelatedList");
        relatedListEvent.setParams({
            "relatedListId": "Cases",
            "parentRecordId": "0016A00000KpavN"
        });
        relatedListEvent.fire();
    }

force:navigateToSObject

Use this event to  Navigates to an sObject record specified by recordId.To display the record view, set the record ID on the recordId attribute and fire the event.The record view contains slides that display the Chatter feed, the record details, and related information. This example displays the related information slide of a record view for the specified record ID.

    <lightning:button variant="success" label="Go to Opportunity" title="Go to Opportunity" onclick="{! c.navigateSobject }"/>

 

  navigateSobject : function (component, event, helper) {
        var navEvt = $A.get("e.force:navigateToSObject");
        navEvt.setParams({
            "recordId": "0066A0000061ziLQAQ",
            "slideDevName": "related"
        });
        navEvt.fire();
    }

force:navigateToURL

Use this system event to navigate the Relative and absolute URL . Relative and absolute URLs are supported. Relative URLs are relative to the Salesforce mobile web domain and retain navigation history. External URLs open in a separate browser window.

    <lightning:button variant="success" label="Navigate To URL" title="Navigate To Salesforce.com" onclick="{! c.navigateToURL }"/>

 

navigateToURL : function(component, event, helper) {
        var urlEvent = $A.get("e.force:navigateToURL");
        urlEvent.setParams({
            "url": 'https://www.salesforce.com/' ,
            "isredirect":true ,
        });
        urlEvent.fire();
    }

 

 

 

Navigation in Lightning Experience Using PageReference

In this blog, I am going to explain how to Use lightning:navigation component to navigate to a given pageReference or to generate a URL from a pageReference. PageReference is a JavaScript object that represents a URL for a page. Use a PageReference instead of attempting to parse or create URLs directly. This approach helps you avoid broken navigation if Salesforce changes URL formats in the future. PageReference provides a well-defined structure that describes the page type and its corresponding attributes. A PageReference object contains key-value pairs to describe the page type you are navigating to.

The following PageReference looks like to set the route to /lightning/o/Account/list?filterName=MyAccounts

var pageReference = {
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'list'
            },
            state: {
                filterName: "MyAccounts"
            }
        };

Example 

The following example generates a URL to an Account Object home based on its pageReference and sets the URL on an <a> element. The example assumes that you’re creating the component for a custom Lightning Component tab or a Lightning page by implementing  force:appHostable  and  flexipage:availableForAllPageTypes

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes">
    <aura:attribute name="url" type="String"/>
    <aura:attribute name="pageReference" type="Object"/>
    <aura:handler name="init" value="{! this }" action="{! c.init }"/>
    <lightning:navigation aura:id="navService"/>
    <a href="{!v.url}">Link</a>
</aura:component>

In your client-side controller, set the pageReference attribute for the Account home page. Set the URL on your link using the generateUrl() method, which is useful for opening links in a new tab. Depending on whether you‚Äôre using the new URL format available as part of the Summer ‚Äô18 critical update, you might see a URL that begins with the new format /lightning/cmp/ or the old format one/one.app#/cmp/.

({
    init : function(cmp, event, helper) {
        var navService = cmp.find("navService");
        var pageReference = {
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'home'
            }
        };
        cmp.set("v.pageReference", pageReference);
        var defaultUrl = "#";
        navService.generateUrl(pageReference)
        .then($A.getCallback(function(url) {
            cmp.set("v.url", url ? url : defaultUrl);
        }), $A.getCallback(function(error) {
            cmp.set("v.url", defaultUrl);
        }));
    },
    
})

 

PageReference is a reference to a page, providing a well-defined structure that describes the page type and its corresponding values. You should use the PageReference definitions instead of attempting to parse the URL directly. The following PageReference properties are supported.

PROPERTY TYPE DESCRIPTION
type string Required. The API name of the PageDefinition.
attributes object Required. Values for each attribute specified by the PageDefinition.
state object Additional parameters, such as filterName, which is tied to the query string of the URL in Lightning Experience. The routing framework doesn’t depend on state to render a page.

 

PageReference Types

A PageReference must be defined with a specific type. The type generates a unique URL format and provides attributes that apply to all pages of that type. The following types are supported.
1 Lightning Component (must implement lightning:isUrlAddressable) 

Example 

{
"type": "standard__component",
"attributes": {
"componentName": "c__MyLightningComponent"
},
"state": {
"myAttr": "attrValue"
}
}

URL formate from the generateUrl method 

/cmp/{componentName}?myAttr=attrValue

 

2 Knowledge Article

A page that interacts with a Knowledge Article record.

Exmaple 

{
"type": "standard__knowledgeArticlePage",
"attributes": {
"articleType": "Briefings",
"urlName": "February-2017"
}
}

URL formate from the generateUrl method 

/articles/{articleType}/{urlName}

3.Named Page

A standard page with a unique name. Only home, chatter, today, and dataAssessment are supported.

Example

{
"type": "standard__namedPage",
"attributes": {
"pageName": "home"
}
}

URL formate from the generateUrl method 

/page/{pageName}

4. Navigation Item Page

A page that displays the content mapped to a CustomTab. Visualforce tabs, Web tabs, Lightning Pages, and Lightning Component tabs are supported.

Example

{
"type": "standard__navItemPage",
"attributes": {
"apiName": "MyCustomTabName"
}
}

URL formate from the generateUrl method 

/n/{devName}

5.Object Page

A page that interacts with an object in the org and supports standard actions for that object.The standard__objectPage type replaces the force:navigateToObjectHome and the force:navigateToList events.

Example

{
type: "standard__objectPage",
attributes: {
objectApiName: "Account",
actionName: "list"
},
state: {
filterName: "Recent"
}
}

URL formate from the generateUrl method 

/r/{objectApiName}/{actionName}?filterName=Recent

6.Record Page

A page that interacts with a record in the org and supports standard actions for that record.The standard__recordPage type replaces the force:navigateToSObject event

Example

{
"type": "standard__recordPage",
"attributes": {
"recordId": "001xx000003DGg0AAG",
"objectApiName": "PersonAccount",
"actionName": "view"
}
}

URL formate from the generateUrl method 

/r/{objectApiName}/{recordId}/{actionName}
/r/{recordId}/{actionName}

7.Record Relationship Page

A page that interacts with a relationship on a particular record in the org. Only related lists are supported.The standard__recordRelationshipPage type replaces the force:navigateToRelatedList event.

Example 

{
"type": "standard__recordRelationshipPage",
"attributes": {
"recordId": "500xx000000Ykt4AAC",
"objectApiName": "Case",
"relationshipName": "CaseComments",
"actionName": "view"
}
}

URL formate from the generateUrl method 

/r/{objectApiName}/{recordId}/related/{relationshipApiName}/{actionName}
/r/{recordId}/related/{relationshipApiName}/{actionName}

 

Dynamically Destroying Lightning Components

In this blog, I am going to show how to destroy a lightning component. The lightning framework automatically destroys it and frees up its memory that is no longer in use at the same time lightning framework will allow destroying the component that is no longer need by using the Component destroy method.
If you create a component dynamically in JavaScript and that component isn’t added to a facet (v.body or another attribute of type Aura.Component[]), you have to destroy it manually using Component.destroy() to avoid memory leaks. The following example shows destroy the use of the framework.

<aura:component >
    <lightning:button variant="brand" label="Create Component" onclick="{! c.handleComponent }" />
    <lightning:button variant="brand" label="Destroying Component" onclick="{! c.handleDestroy }" />
    <lightning:button variant="brand" label="Destroying Component wit facet" onclick="{! c.handleDestroywithfacet }" />
    
    {!v.body}
</aura:component>
({
    handleComponent : function(component, event, helper) {
        $A.createComponent(
            "ui:inputText",
            {
                "aura:id": "inpId",
                "labelClass":"slds-form-element__label",
                "placeholder":"Enter Some Text",
                "label": "Enter some text",
                "class": "slds-input"
            },
            function(newInp, status, errorMessage){
                if (status === "SUCCESS") {
                    var body = component.get("v.body");
                    body.push(newInp);
                    component.set("v.body", body);
                }
                else if (status === "INCOMPLETE") {
                    console.log("No response from server or client is offline.")
                }
                    else if (status === "ERROR") {
                        console.log("Error: " + errorMessage);
                    }
            }
        );
    },
    handleDestroy : function(component,event,helper){
        if(component.find("inpId")!=null || component.find("inpId")!='undefined'){
            component.find("inpId").destroy();
        }else{
            alert(' Component is already Destroyed ');
        }
        
    },
    handleDestroywithfacet : function(component,event,helper){
        var body = component.get("v.body");
        body.shift();
        component.set("v.body", body);
        
    }
})

In this example, I have created a two button. The Destroying Component button will destroy the component using the destroy method.

handleDestroy : function(component,event,helper){
        if(component.find("inpId")!=null || component.find("inpId")!='undefined'){
            component.find("inpId").destroy();
        }else{
            alert(' Component is already Destroyed ');
        }
        
    },

Similarly Destroying Component wit facet method will be another way of cleaning the component by using facet with below code.

 handleDestroywithfacet : function(component,event,helper){
        var body = component.get("v.body");
        body.shift();
        component.set("v.body", body);
        
    }

 

 

 

Dynamically Creating Lightning Components

In this post, I am going to show how to create a lightning component dynamically by using javascript controller. Create a component dynamically in your client-side JavaScript code by using the $A.createComponent() method. To create multiple components, use $A.createComponents().$A.createComponent Syntax is looking as shown below.

$A.createComponent(String type, Object attributes, function callback)
  1. type‚ÄĒThe type of component to create; for example, “ui:button”.
  2. attributes‚ÄĒA map of attributes for the component, including the local Id (aura:id).
  3. callback(cmp, status, errorMessage)‚ÄĒThe callback to invoke after the component is created

In this example, The client-side controller calls $A.createComponent() to create a ui:inputText with a local ID. The function(newInp, status, errorMessage) callback appends the inputText to the body of c:createComponent.

<aura:component >
    <lightning:button variant="brand" label="Create Component" onclick="{! c.handleComponent }" />
    {!v.body}
</aura:component>
({
    handleComponent : function(component, event, helper) {
        $A.createComponent(
            "ui:inputText",
            {
                "aura:id": "inpId",
                "labelClass":"slds-form-element__label",
                "placeholder":"Enter Some Text",
                "label": "Enter some text",
                "class": "slds-input"
            },
            function(newInp, status, errorMessage){
                if (status === "SUCCESS") {
                    var body = component.get("v.body");
                    body.push(newInp);
                    component.set("v.body", body);
                }
                else if (status === "INCOMPLETE") {
                    console.log("No response from server or client is offline.")
                }
                    else if (status === "ERROR") {
                        console.log("Error: " + errorMessage);
                    }
            }
        );
    },
})

Creating Nested Components

To dynamically create a component in the body of another component, use $A.createComponents() to create the components. In the function callback, nest the components by setting the inner component in the body of the outer component.

<aura:component >
    <lightning:button variant="brand" label="Create Components" onclick="{! c.handleComponent }" />
    {!v.body}
</aura:component>
({
    handleComponent : function(component, event, helper) {
        $A.createComponents([
            ["ui:outputText",{
                "value" :"Message1"
            }],
            ["ui:outputText",{
                "value" : "Message2"
            }],
            ["ui:outputText",{
                "value" :"Message3"
            }]
        ],
                            function(components, status, errorMessage){
                                if (status === "SUCCESS") {
                                    var body = component.get("v.body");
                                    components.forEach(function(item){
                                        body.push(item);
                                    });
                                    component.set("v.body", body);
                                }
                                else if (status === "INCOMPLETE") {
                                    console.log("No response from server or client is offline.")
                                }
                                    else if (status === "ERROR") {
                                        console.log("Error: " + errorMessage);
                                    }
                            }
                           );
    },
})

The dynamic lightning component will be an option in case if you wanted to create lightning components dynamically by using client-side javascript.

 

 

lightning:fileUpload Example

A¬†lightning:fileUpload¬†component provides an easy and integrated way for users to upload multiple files. The file uploader includes drag-and-drop functionality and filtering by file types. File uploads are always associated to a record, hence the¬†recordId¬†attribute is required. Uploaded files are available in Files Home under the Owned by Me filter and on the record’s Attachments related list on the record detail page. Although all file formats that are supported by Salesforce are allowed, you can restrict the file formats using the¬†accept¬†attribute. Here is the example code .

Lightnin Component 

<aura:component implements="force:hasRecordId,flexipage:availableForAllPageTypes" access="global" >
    <aura:attribute name="accept" type="List" default="['.jpg', '.jpeg']"/>
    <aura:attribute name="multiple" type="Boolean" default="true"/>
    <aura:attribute name="disabled" type="Boolean" default="false"/>
                    
    <lightning:fileUpload label="Add attachment" multiple="{!v.multiple}" 
                          accept="{!v.accept}" recordId="{!v.recordId}" 
                          onuploadfinished="{!c.handleUploadFinished}" />
    
</aura:component>

Controller 

({
    handleUploadFinished : function(component, event, helper) {
        var uploadedFiles = event.getParam("files");
        var documentId = uploadedFiles[0].documentId;
        var fileName = uploadedFiles[0].name;
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "title": "Success!",
            "message": "File "+fileName+" Uploaded successfully."
        });
        toastEvent.fire();
        
        $A.get('e.lightning:openFiles').fire({
            recordIds: [documentId]
        });
        
    }
})

 

Code walkthrough 

  1. event.getParam(“files”)¬†returns a list of uploaded files with the properties¬†name¬†and¬†documentId.name: The file name in the format¬†filename.extension.documentId: The ContentDocument Id in the format¬†069XXXXXXXXXXXX.
        var uploadedFiles = event.getParam("files");
        var documentId = uploadedFiles[0].documentId;
        var fileName = uploadedFiles[0].name;

2. Below code will show the Toast on Successfully file upload

var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "title": "Success!",
            "message": "File "+fileName+" Uploaded successfully."
        });
        toastEvent.fire();

3.below code will open the file preview after file upload.

 $A.get('e.lightning:openFiles').fire({
            recordIds: [documentId]
        });

File Upload Limits

By default, you can upload up to 10 files simultaneously unless your Salesforce admin has changed that limit. The org limit for the number of files simultaneously uploaded is a maximum of 25 files and a minimum of 3 files. The maximum file size you can upload is 2 GB. In Communities, the file size limits and types allowed follow the settings determined by community file moderation. Guest user can’t add files.

Usage Considerations

This component is not supported in Lightning Out or standalone apps, and displays as a disabled input. Additionally, if the Don't allow HTML uploads as attachments or document records security setting is enabled for your organization, the file uploader cannot be used to upload files with the following file extensions: .htm, .html, .htt, .htx, .mhtm, .mhtml, .shtm, .shtml, .acgi, .svg.