Sunday, 16 June 2019

Eevnts in salesforce lightning

Lightning Events can be classified into 3 types

1.system Events
2.Custom Events
3.Lightning Application Events from Library


System Events in Lightning Framework :
=======================================
System events are fired automatically by lightning framework and during component initialization, rendering or attribute value change etc.

No need to register the event and also no need to fire the event manually.system will do for us.

1. aura:valueInit

This event automatically fired once the component instance successfully created.

or

This event is fired when an app or component is initialized, prior to rendering . Handle this event using the aura:handler tag.

ex :

<aura:handler name="init" value="{!this} action={!c.doInit}"></aura:handler>



2. aura:valueChange

This event automatically fired once the component  attribute value changed.

This event is fired when an attribute value changes.Handle this event using the aura:handler tag.

<aura:handler name="change" value="{!v.items}" action="{!c.handlevalueChange}" />

The valueChange event gives you access to the previous value and the current value.

handleValueChange : function (component, event, helper) {
        alert("old value: " + event.getParam("oldValue"));
        alert("current value: " + event.getParam("value"));
    }

3. aura:valueRender

Indicates that an app or component has been rendered or rerendered.

This event is fired when an app or component is rendered or rerendered. Handle this event using the aura:handler tag.

<aura:handler name="render" value="{!this}" action="{! c.handleValueRender}"></aura:handler>

The render event is fired after the init event,which is fired after component construction but before rendering.

4. aura:valueDestroy

Indicates that a component has been destroyed.

This event is fired when a component is destroyed . handle this event if you need to do custom cleanup when a component is destroyed.

<aura:handler name="destroy" value="{!this}" action="{! c.handleDestroy}" />

The aura:valueDestroy event is triggered when you tap on a different menu item on the salesforce mobile navigation menu, and your component  is destroyed.

5. aura:noaccess


6. aura:locationChange

Indicates that the hash part of the URL has changed.

This event is fired when the hash part of the URL has changed. Handle this event using the aura:handler tag.

<aura:handler event="aura:locationChange" action="{! c.update}" />

update : function (component,event,helper){
      var loc = event.getParam("token");
}

aura:locationChange tracks changes to the hash fragment in the url, it's not useful for tracking navigation with the new URL format.

7. aura:doneRendering
 This event is automatically fired if no more components  need to be rendered or rerendered due to any attribute  value changes. (OR) Indicates that the initial rendering  of the root application has completed.

For example, you want to customize the behavior of your app after it’s finished rendering the first time but not after subsequent rerenderings.     Create an attribute to determine if it’s the first rendering.


 ex :
  <aura:handler event="aura:doneRendering" action="{!c.doneRendering}"/>
  <aura:attribute name="isDoneRendering" type="Boolean" default="false"/>

   doneRendering: function(cmp, event, helper) {
    if(!cmp.get("v.isDoneRendering")){
      cmp.set("v.isDoneRendering", true);
      //do something after component is first rendered
    }
  }
 
  This client-side controller checks that the aura:doneRendering    event has been fired only once.
 
8. aura:donewaiting

This event automatically fired when all server response (apex) complete.
aura:donewaiting indicate that the lightning component is done waiting for server response.

or

The aura:doneWaiting application event is fired for every server response , even for responses from other components in your app.

This event is automatically fired if no more response from the server is expected.

 <aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>
 <ui:spinner aura:id="spinner"/>

 hideSpinner : function (component, event, helper) {
        var spinner = component.find('spinner');
        var evt = spinner.get("e.toggle");
        evt.setParams({ isVisible : false });
        evt.fire();   
    }




9. aura:systemError

This event is automatically fired when an error is encountered during the execution of a server-side action.

ex :

<aura:handler event="aura:systemError" action="{!c.showSystemError}"/>
<aura:attribute name="response" type="Aura.Action"/>
<lightning:button aura:id="trigger" label="Trigger error" onclick="{!c.trigger}"/>

This client-side controller triggers the firing of an error  and handles that error.

trigger: function(cmp, event) {
        // Call an Apex controller that throws an error
        var action = cmp.get("c.throwError");
        action.setCallback(cmp, function(response){
            cmp.set("v.response", response);
        });
        $A.enqueueAction(action);
    },
    showSystemError: function(cmp, event) {
        // Handle system error
    }

10. aura:waiting

The aura:waiting event is deprecated.Execute logic after queueing an action instead of using this event.A component is waiting for a response for an action until the
action's callback is invoked.


<aura:handler event="aura:waiting" action="{!c.showSpinner}"/>
 <ui:spinner aura:id="spinner"/>

showSpinner : function (component, event, helper) {
        var spinner = component.find('spinner');
        var evt = spinner.get("e.toggle");
        evt.setParams({ isVisible : true });
        evt.fire();   
    }

Note : The aura:doneWaiting application event is fired for every server request,
even for requests from other components in your app.



Custom Events :
===============
1.Application Events

Application events follow a traditional publish-subscribe model.An application event is fired from an instance of a component.All components that provide a handler for the event are notified.

sequence of application event propagation  :

1. Event fired - An application event is fired. The component that fires the event is known as the source component.

2.Capture phase - The framework executes the capture phase from the application root to the source component until all components are traversed.Any handling event can stop propagation by calling
stopPropagation() on the event.

3.Bubble phase - The framework executes the bubble phase from the source component to the application root until all components are traversed or stopPropagation() is called.

4.Default phase - The framework executes the default phase from the root node unless preventDefault() was called in the capture  or bubble phases. If the event's propagation wasn't stopped in a previous phase, the root node defaults to the application root.If the event's propagation was stopped in a previous phase, the root node is set to the component whose handler invoked
event.stopPropagation().


Note :
The default application events are handled in a non-deterministic order, which just means we should not rely on the order in which the handlers receive the event.


2.Component Events

The component that fires an event is known as the source component.

Sequence of Component event Propagation :

1.Event fired - A component event is fired.

2.Capture Phase - The framework executes the capture phase from the application root to the source component until all components are traversed.
Any Handling event can stop propagation by calling stopPropagation() on the event.

3.Bubble Phase - The framework executes the bubble phase from the source component to the application root until all components are traversed or stopPropagation() is called.

By default ,component events are handled in the bubble phase , and that's what most developers use.
To handle capture phase, add a phase ="capture" attribute  to your event handler.

ex :

<aura:handler name="cmpEvent" event="c:cmpEvent" action="{! c.handleCmpEvent}" Phase="capture" />

To get the events current propagation phase by calling event.getphase() in your handling function which in-turn will either return capture or bubble.

 handleCmpEvent : function(component, event) {
    var phase = event.getPhase();
 }

 By default , in Lightning component hierarchy only parent  components that create subcomponents (either in their markup   or programmatically ) can handle events which does not include
 container component.

 ex :

 <!-- Owner -->
 <aura:component>
   <c:container>
      <c:eventEmitter></c:eventEmitter>
   </c:container>
 </aura:component>

 If you want a container component to handle a component event,  add an includeFacets="true" attribute to its handler

 <!--c:container component -->
 <aura:component>

  <aura:handler name="cmpEvent" event="c:cmpEvent"
    action="{! c.handleCmpEvent}" includeFacets="true" />
   {! v.body }
 </aura:component>

 You can stop the event at any point by calling   event.stopPropagation() regardless of the current
 propagation phase.

 Lightning Framework also gives us an option to resume  and pause the event which can be a typical use case  for this is asynchronous processing.

 handleEvent:function(component, event, helper){
    event.pause();
    Var action = $component.get(“c.getABeer”);
    action.setcallback(this, function(response){
     if(response.getState() == “SUCCESS”) {
        event.resume();
      }  else if (state === "ERROR") {
       event.stopPropagation();
    }
});
   $A.enqueueAction(action);

}


Note :
1.The event handler and event registration name attribute is name.It should be same to bind the event
registration with event handler.

2. Capture event handler is fired first before bubble event handler. if event.stopPropagation is called from capture event handler then all other event handler including all bubble event handler are cancelled and not executed.


Lightning Application Events  From Library:
===========================================
1. force:closeQuickAction
2. force:createRecord
3. force:editRecord
4. force:navigateToComponent
5. force:navigateToList
6. force:navigateToObjectHome
7. force:navigateToRelatedList
8. force:navigateToSObject
9. force:navigateToURL
10. force:recordSave
11. force:recordSaveSuccess
12. force:refreshView
13. force:showToast
14. lightning:openFiles

Quick Actions/ Lightning Actions :
==================================
create and update records related to existing records.

Quick Action/Lightning Actions is an object-specific action.Object-specific actions let users create records that have  automatic relationships to other records, make updates to specific records.

To display a lightning component as a Quick action to an object, it must be implemented with

force:lightningQuickAction (or)
force:lightningQuickActionWithoutHeader

Note :
1. we cannot add both force:lightningQuickAction and force:lightningQuickActionWithoutHeader action to a single lightning component.
2.we cannot add lighning application as a quick action.

To close action Manually

var dismissActionPanel = $A.get("e.force:closeQuickAction");
dismissActionPanel.fire();

After closing quick action panel refresh the main view

$A.get('e.force:refreshView').fire();


force:createRecord in Salesforce Lightning :
===============================

Opens a page to create a record for the specified entityApiName

ex : Account,MyObject__c

 var createRecordEvent = $A.get('e.force:createRecord');
        if ( createRecordEvent ) {
            createRecordEvent.setParams({
                'entityApiName': 'Account',
                'defaultFieldValues': {
                    'Type' : 'Prospect',
                    'Industry' : 'Apparel',
                    'Rating' : 'Hot'
                }
            });
            createRecordEvent.fire();

force:editRecord in Salesforce Lightning :
==============================

Opens the page to edit the record specified by recordId


 var editRecordEvent = $A.get("e.force:editRecord");
        editRecordEvent.setParams({
             "recordId": component.get("v.recordId")
       });
       editRecordEvent.fire();
    }

force:navigateToComponent in salesforce Lightning :
====================================
Navigates from one Aura component to another.

 var evt = $A.get("e.force:navigateToComponent");
        evt.setParams({
            componentDef : "c:ComponentTwo",
            componentAttributes: {   
                Text : component.get("v.Txt")
            }
        });
        evt.fire();


force:navigateToList in salesforce Lightning :
================================
To navigate to a list view , set the list view ID on the listViewId attribute and fire the event.

@AuraEnabled
public static List<ListView> getListViews() {
    List<ListView> listviews =
        [SELECT Id, Name FROM ListView WHERE SobjectType = 'Contact'];
   
    return listviews;
}

gotoList : function (component, event, helper) {
    var action = component.get("c.getListViews");
    action.setCallback(this, function(response){
        var state = response.getState();
        if (state === "SUCCESS") {
            var listviews = response.getReturnValue();
            var navEvent = $A.get("e.force:navigateToList");
            navEvent.setParams({
                "listViewId": listviews.Id,
                "listViewName": null,
                "scope": "Contact"
            });
            navEvent.fire();
        }
    });
    $A.enqueueAction(action);
}

force:navigateToObjectHome in salesforce Lightning :
=====================================
This event enables you to navigate to the object home specified by the scope attribute.

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

force:navigateToRelatedList in salesforce Lightning :
====================================
Navigates to the related list specified by parentRecordId.

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

force:navigateToSObject in salesforce Lightning :
===================================

Use this event to Navigate to an sObject record specified by record Id.

slideDevName : Specifies the slide within the record view to display initially .

Valid Options are :

1.detail : The record detail slide .This is the default value.
2.chatter : The Chatter slide
3.related : The related information slide.

 gotoSObjectdetail : function(component, event, helper) {
 var navEvent = $A.get("e.force:navigateToSObject"); 
        navEvent.setParams({
            "recordId": component.get("v.accId"), 
            "slideDevName": "detail"
        });       
        navEvent.fire();
}

force:navigateToURL in salesforce Lightning :
=================================

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.

ex :

GotoURL : function(component, event, helper) {
        var viewRecordEvent = $A.get("e.force:navigateToURL");
        viewRecordEvent.setParams({
            "url": "/006/o"
        });
        viewRecordEvent.fire();
    },
 GotoGoogle :function(component, event, helper) {
             
        var urlEvent = $A.get("e.force:navigateToURL");
        urlEvent.setParams({
            "url": 'https://www.google.com/maps/place/' + 'Hyderabad, Telangana'
        });
        urlEvent.fire();
    }

force:

force:recordSaveSuccess is used with the force:recordEdit component

1. e.recordSave is used to fire the save event of force:recordEdit.
2. force:recordSaveSuccess event is used with onSaveSuccess after the record is successfully updated. Fired when  record saving was successful.

ex :

<aura:component>
 <aura:attribute name="isErrorOnSave" type="Boolean" default="false" />
 <aura:handler name="onSaveSuccess" event="force:recordSaveSuccess" action="{!c.handleSaveSuccess}"/>
 <aura:handler event="aura:doneWaiting" action="{!c.handleDoneWaiting}"/>

  <aura:attribute name="account" type="Account" />
    <force:recordEdit aura:id="edit" recordId="{!v.account.Id}"/>
    <lightning:button label="Save" onclick="{!c.save}"></lightning:button>
</aura:component>

save  : function(component, event, helper) {
        component.set(“v.isErrorOnSave”, true);
component.find("edit").get("e.recordSave").fire();

},
 handleSaveSuccess : function(component, event, helper) {
   // because there were no errors
   // handle save success
 
   component.set(“v.isErrorOnSave”, false);
 
    var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "title": "Success!",
            "message": "The record has been updated successfully."
        });
        toastEvent.fire();
 
   },
handledoneWaiting : function(component, event, helper) {
 // if there were errors during save,
 // the handleSaveSuccess doesn’t get fired
  if(component.get(“v.isErrorOnSave”) === true) {
           var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "title": "Error",
            "message": "The record is not saved."
        });
        toastEvent.fire();
    }
  }
 
 lightning:openFiles in salesforce lightning   :
 ===============================
 open the file and preview after file upload


 ex :

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

No comments:

Post a Comment