This post explains how to use the lightning:unsavedChanges component in lightning.
This component provides a way to notify the UI containment hierarchy of unsaved changes and to participate in saving or discarding those changes based on the user's decision.
UnsavedChangesComponentDemohelper
This component provides a way to notify the UI containment hierarchy of unsaved changes and to participate in saving or discarding those changes based on the user's decision.
Example:
UnsavedChangesComponentDemo
<aura:component implements="flexipage:availableForRecordHome" access="global">
<lightning:unsavedChanges aura:id="unsaved"
onsave="{!c.handleSave}"
ondiscard="{!c.handleDiscard}" />
<!-- Notification library to show notifications-->
<lightning:notificationsLibrary aura:id="notifLib"/>
<div class="slds-theme_default">
<center>
<p style="font-size:medium;font-family:sans-serif;padding:10px;margin:5px">Create New Account</p>
</center>
<lightning:recordEditForm aura:id="form"
onsuccess="{!c.handleSuccess}"
onsubmit="{!c.handleSubmit}"
objectApiName="Account">
<!-- the messages component is for error messages -->
<lightning:messages />
<lightning:inputField fieldName="Name" onchange="{!c.handleDataChange}"/>
<lightning:inputField fieldName="Industry" onchange="{!c.handleDataChange}" />
<lightning:inputField fieldName="Type" onchange="{!c.handleDataChange}" />
<lightning:inputField fieldName="Phone" onchange="{!c.handleDataChange}" />
<lightning:inputField fieldName="Emil" onchange="{!c.handleDataChange}"/>
<center>
<div class="slds-m-top_medium">
<lightning:button variant="brand" type="submit" name="save" label="Save New Account" />
</div>
</center>
</lightning:recordEditForm>
</div>
</aura:component>
UnsavedChangesComponentDemoController
({
handleDataChange : function(component, event, helper) {
helper.dataChange(component, event, helper);
},
handleSubmit : function(component, event, helper) {
helper.submitData(component, event, helper);
},
handleSave : function(component, event, helper) {
helper.submitData(component, event, helper);
},
handleDiscard : function(component, event, helper) {
// similar to the handleSave method, but for discarding changes
},
handleSuccess : function(component, event, helper) {
helper.handleSuccess(component, event, helper);
}
})
UnsavedChangesComponentDemohelper
({
dataChange : function(component, event, helper) {
var unSavedChange = component.find('unsaved');
unSavedChange.setUnsavedChanges(true, { label: 'You have unsaved changes. Do you want to Continue?' });
},
submitData : function(component, event, helper) {
var unSavedChange = component.find('unsaved');
unSavedChange.setUnsavedChanges(false);
},
handleSuccess : function(component, event, helper) {
var record = event.getParams().response;
component.find('notifLib').showToast({
"variant": "success",
"title": record.fields.Name.value,
"message": "The record has created successfully."
});
}
})
Demo
Happy Learning!!!