Showing posts with label Lightning Components. Show all posts
Showing posts with label Lightning Components. Show all posts
Tuesday, June 25, 2019
Saturday, March 9, 2019
How to access apex class properties in lightning components
This post explains how to access apex class properties in the lightning component.
Example:
Lightning Component
Lightning Component ControllerExample:
Lightning Component
<aura:component controller="LightningDemoController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
<aura:attribute name="objClass" type="LightningDemoController" />
<aura:handler name="init" value="{!this}" action="{!c.getAccRecors}" />
<!-- Notification Library to show notices and toast messages-->
<lightning:notificationsLibrary aura:id="notifLib"/>
<lightning:card title="Account Records">
<p>
User Name: <b>{!v.objClass.strUserName}</b>
</p><br/>
<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" title="Id">Id</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Name">Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Industry">Industry</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Phone">Phone</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.objClass.lstAccs}" var="ac">
<tr>
<th scope="row">
<div class="slds-truncate" title="{#ac.Id}">{!ac.Id}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{#ac.Name}">{!ac.Name}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{#ac.Industry}">{!ac.Industry}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{#ac.Phone}">{!ac.Phone}</div>
</th>
</tr>
</aura:iteration>
</tbody>
</table>
</lightning:card>
</aura:component>
({
getAccRecors : function(component, event, helper) {
var action = component.get('c.retriveAccInfo');
action.setCallback(this, function(response) {
if(response.getState() === 'SUCCESS') {
var result = response.getReturnValue();
component.set('v.objClass', result);
if(result.lstAccs) {
component.find('notifLib').showToast({
"variant": "success",
"title": "Success!",
"message": "Account Retrived successfully."
});
}
}
});
$A.enqueueAction(action);
}
})
Apex Class
public inherited sharing class LightningDemoController {
@AuraEnabled public String strUserName {get;set;}
@AuraEnabled public list<Account> lstAccs {get;set;}
@AuraEnabled
public static LightningDemoController retriveAccInfo() {
LightningDemoController obj = new LightningDemoController();
obj.strUserName = UserInfo.getName();
obj.lstAccs = [SELECT Id, Name, Industry, Phone FROM Account limit 10];
return obj;
}
}
Result
Friday, January 18, 2019
How to import Current User id in Lightning Web Components(lwc)
This post explains the how to import current user id in lightning web components
To import current user id we use the @salesforce/user/Id scoped module.
Example
LWCCurrentUserIdDemo.html
LWCCurrentUserIdDemo.js
LWCCurrentUserIdDemo.js-meta.xml
Happy Learning!!!
To import current user id we use the @salesforce/user/Id scoped module.
Syntax
import userId from '@salesforce/user/Id';
Example
LWCCurrentUserIdDemo.html
<template>
<lightning-card title="CurrentUserId" icon-name="custom:custom19">
<div class="slds-m-around_medium">
<p>User Id:</p>
<b>{userId}</b>
</div>
</lightning-card>
</template>
LWCCurrentUserIdDemo.js
import { LightningElement } from 'lwc';
import Id from '@salesforce/user/Id';
export default class LWCCurrentUserIdDemo extends LightningElement {
userId = Id;
}
LWCCurrentUserIdDemo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="LWCCurrentUserIdDemo">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
ResultHappy Learning!!!
Saturday, January 5, 2019
wire service in Lightning Web Components(LWC)

What is the wire service?
- Lightning web components(lwc) use reactive wire service to read Salesforce data.
- It is Built on Lightning Data service.
- Components use @wire in their JavaScript class to read data from one of the wire adapters in the lightning/ui*Api namespace.
wire service syntax
import { adapterId } from 'adapterModule';
@wire(adapterId, adapterConfig)
propertyOrFunction;
adapterId (Identifier) ---> The identifier of the wire adapter.
adapterModule (String) —>The identifier of the module that contains the wire adapter function, in the format namespace/moduleName.
adapterConfig (Object) —> A configuration object specific to the wire adapter. Configuration object property values can be either strings or references to objects and fields imported from @salesforce/schema.
propertyOrFunction —> A private property or function that receives the stream of data from the wire service.
- If a property is decorated with @wire, the results are returned to the property’s data property or error property.
- If a function is decorated with @wire, the results are returned in an object with a data property and an error property.
Example
Import references to salesforce Object and fields
1. To import a reference to an object, use this syntax.
import objectName from '@salesforce/schema/object';
Ex:
import PROPERTY_OBJECT from '@salesforce/schema/Property__c';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
2. To import a reference to a field, use this syntax.import FIELD_NAME from '@salesforce/schema/object.field';
Ex:import POSITION_LEVEL_FIELD from '@salesforce/schema/Property__c.Name';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';
3. To import a reference to a field via a relationship, use this syntax.import SPANNING_FIELD_NAME from '@salesforce/schema/object.relationship.field';
import ACCOUNT_OWNER_NAME_FIELD from '@salesforce/schema/Account.Owner.Name';
Decorate a Property with @wire
- Wiring a property with @wire is useful when you want to consume the data or error.
- If the property decorated with @wire is used as an attribute in the template and its value changes,
- the wire service provisions(requests) the data and triggers the component to rerender.
Ex:
import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
export default class Record extends LightningElement {
@api recordId;
@wire(getRecord, { recordId: '$recordId', fields: ['Opportunity.Name'] })
record;
}
Decorate a Function with @wire
- Wiring a function is useful to perform logic whenever new data is provided or when an error occurs.
- The function is invoked whenever a value is available, which can be before or after the component is connected or rendered.
Ex:
import { LightningElement, api, track, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
export default class WireFunction extends LightningElement {
@api recordId;
@track record;
@track error;
@wire(getRecord, { recordId: '$recordId', fields: ['Opportunity.Name'] })
wiredAccount({ error, data }) {
if (data) {
this.record = data;
} else if (error) {
this.error = error;
}
}
}
Resource
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.data_wire_service_about
Happy Learning!!!
Sunday, December 9, 2018
lightning:fileUpload component in lightning
This post explains how to use lightning:fileupload in lighting component
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.
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.
Limitations
- By default we can upload max 10 files, Admins can contact Salesforce to request a changeup to a maximum of 25 files uploaded at one time
- The maximum file size we can upload is 2 GB.
- Guest users can't add files to Communities
Note:
1. This component is not supported in Lightning Out or standalone apps.
2. we can't upload files with the following file extensions: .htm, .html, .htt, .htx, .mhtm, .mhtml, .shtm, .shtml, .acgi, .svg
1. This component is not supported in Lightning Out or standalone apps.
2. we can't upload files with the following file extensions: .htm, .html, .htt, .htx, .mhtm, .mhtml, .shtm, .shtml, .acgi, .svg
File Uploder Example
FileuploaderComponent
<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
<lightning:notificationsLibrary aura:id="notifLib"/>
<div class="slds-theme_default">
<lightning:fileUpload title="Upload Files"
name="fileuploader"
label="Upload Files"
recordId="{!v.recordId}"
multiple="true"
accept=".pdf,.png,.jpg"
onuploadfinished="{!c.afterFinish}"/>
</div>
</aura:component>
FileUploaderComponentController.js
({
afterFinish : function(component, event, helper) {
// Geting the list of uploaded files
var uploadFiles = event.getParam("files");
var strFileNames = '';
// getting uploaded file names
for(var i=0; i<uploadFiles.length; i++) {
strFileNames += uploadFiles[i].name + ', ';
}
// Showing Success message
component.find("notifLib").showToast({
"variant": "success",
"title": strFileNames,
"message": uploadFiles.length + " Files are Uploaded Successfully!"
});
$A.get("e.force:refreshView").fire();
}
})
Demo
Let us Know if you have any queries
Happy Learning!!
Happy Learning!!
Monday, December 3, 2018
Show Modal box using lightning:overlayLibrary in Lightning component
This Post explains the how to show modal box using lightning:overlayLibrary
What is Modal?
1. Modal blocks everything else on the page until it’s dismissed.
2. Modal is triggered by user interaction, which can be a click of a button or link.
3. The modal header, body, and footer are customizable. Pressing the Escape key or clicking the close button closes the modal.
Demo:
OverlayLibrarydemoComponent
What is Modal?
1. Modal blocks everything else on the page until it’s dismissed.
2. Modal is triggered by user interaction, which can be a click of a button or link.
3. The modal header, body, and footer are customizable. Pressing the Escape key or clicking the close button closes the modal.
Demo:
OverlayLibrarydemoComponent
<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
<aura:attribute name="strRecId" type="String" />
<lightning:overlayLibrary aura:id="overlayLibDemo"/>
<div class="slds-theme_default">
<p>
<h1>Lightning OverlayLibrary Example</h1>
<lightning:button variant="brand" label="Account Edit" title="Account Edit" onclick="{!c.showModal}" />
</p>
</div>
</aura:component>
OverlayLibrarydemoComponentController
({
showModal : function(component, event, helper) {
helper.showModalHelper(component, event, helper);
}
})
OverlayLibrarydemoComponentHelper
({
showModalHelper : function(component, event, helper) {
var strAccId = component.get("v.recordId");
console.log('Account Id ====>'+strAccId);
$A.createComponent("c:AccountEditComponent",
{strRecordId : strAccId},
function(result, status) {
if (status === "SUCCESS") {
component.find('overlayLibDemo').showCustomModal({
header: "Account Edit Form",
body: result,
showCloseButton: true,
cssClass: "mymodal",
})
}
});
}
})
OverlayLibrarydemoComponent.css
.THIS {
text-align: center;
vertical-align: middle;
line-height: 90px;
font-size: 20Px;
}
below component shows in the modal box when clicking the button
AccountEditComponent
<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
<aura:attribute name="strRecordId" type="String" />
<lightning:overlayLibrary aura:id="overlayLibDemo1"/>
<lightning:notificationsLibrary aura:id="notifLib"/>
<div class="slds-theme_default">
<lightning:recordEditForm aura:id="editform"
onsubmit="{!c.handleSubmit}"
onsuccess="{!c.handleSuccess}"
recordId="{!v.strRecordId}"
objectApiName="Account">
<lightning:messages />
<lightning:inputField fieldName="Name" aura:id="accName" />
<lightning:inputField fieldName="Industry" />
<lightning:inputField fieldName="Phone" />
<lightning:inputField fieldName="Type" />
<div class="slds-m-top_medium">
<lightning:button variant="brand" type="submit" name="save" label="Save" />
</div>
</lightning:recordEditForm>
</div>
</aura:component>
AccountEditComponentController({
handleSubmit : function(component, event, helper) {
component.find('editform').submit();
},
handleSuccess : function(component, event, helper) {
var strAccName = component.find("accName").get("v.value");
component.find('notifLib').showToast({
"variant": "success",
"title": strAccName,
"message": "Account Updated Successfully!!"
});
component.find("overlayLibDemo1").notifyClose();
},
})
Let us Know if you have any queries
Happy Learning!!
Tuesday, October 30, 2018
lightning:notificationsLibrary in lightning
This post explains the use of lightning:notificationLibrary in lightning component
lightning:notificationLibrary is supported in Lightning Experience, Salesforce app, and Lightning communities.
include one <lightning:notificationsLibrary aura:id=”notifLib”/> tag in the component that triggers all the notifications, and aura:id is a unique local id in the component.
Messages can be displayed in notices and toasts.
Notices
Toasts
Demo
Check below code sample for more information
Happy Learning!!!
lightning:notificationLibrary is supported in Lightning Experience, Salesforce app, and Lightning communities.
include one <lightning:notificationsLibrary aura:id=”notifLib”/> tag in the component that triggers all the notifications, and aura:id is a unique local id in the component.
Messages can be displayed in notices and toasts.
Notices
- Notices alert users to system-related issues and updates.
- Notices interrupt the user's workflow and block everything else on the page. Notices must be acknowledged before a user regains control over the app again.
- To dismiss the notice, only the OK button is currently supported.
Toasts
- Toasts enable you to provide feedback and serve as a confirmation mechanism after the user takes an action.
- Toasts are less intrusive than notices and are suitable for providing feedback to a user following an action, such as after a record is created.
- A toast can be dismissed or can remain visible until a predefined duration has elapsed.
Demo
To create and display a notice, pass in the notice attributes using component.find('notifLib').showNotice(), where notifLib matches the aura:id on the lightning:notificationsLibrary instance.
To create and display a toast, pass in the toast attributes using component.find('notifLib').showToast(), where notifLib matches the aura:id on the lightning:notificationsLibrary instance.
Check below code sample for more information
Lightning Component
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
<lightning:notificationsLibrary aura:id="notifLib"/>
<lightning:buttonGroup>
<lightning:button variant="Neutral" label="Notice Info" onclick="{!c.showNoticeInfo}"/>
<lightning:button variant="Neutral" label="Notice Error" onclick="{!c.showNoticeError}"/>
<lightning:button variant="Neutral" label="Notice Warning" onclick="{!c.showNoticeWarning}"/>
<lightning:button variant="Neutral" label="Toast Info" onclick="{!c.showToastInfo}"/>
<lightning:button variant="Neutral" label="Toast Warning" onclick="{!c.showToastWarning}"/>
<lightning:button variant="Neutral" label="Toast Success" onclick="{!c.showToastSuccess}"/>
<lightning:button variant="Neutral" label="Toast Error" onclick="{!c.showToastError}"/>
</lightning:buttonGroup>
</aura:component>
Javascript Controller({
showNoticeInfo : function(component, event, helper) {
component.find('notifLib').showNotice({
"variant": "info",
"header": "Something has gone wrong!",
"message": "Unfortunately, there was a problem updating the record.",
});
},
showNoticeError : function(component, event, helper) {
component.find('notifLib').showNotice({
"variant": "error",
"header": "Something has gone wrong!",
"message": "Unfortunately, there was a problem updating the record.",
});
},
showNoticeWarning : function(component, event, helper) {
component.find('notifLib').showNotice({
"variant": "warning",
"header": "Something has gone wrong!",
"message": "Unfortunately, there was a problem updating the record.",
});
},
showToastInfo : function(component, event, helper) {
component.find('notifLib').showToast({
"variant": "info",
"title": "Notif library Info!",
"message": "The record has been updated successfully."
});
},
showToastWarning : function(component, event, helper) {
component.find('notifLib').showToast({
"variant": "warning",
"title": "Notif library Warning!",
"message": "The record has been updated successfully."
});
},
showToastSuccess : function(component, event, helper) {
component.find('notifLib').showToast({
"variant": "success",
"title": "Notif library Success!",
"message": "The record has been updated successfully."
});
},
showToastError : function(component, event, helper) {
component.find('notifLib').showToast({
"variant": "error",
"title": "Notif library Error!",
"message": "The record has been updated successfully."
});
},
})
Let us know if you have any queries.Happy Learning!!!
Sunday, September 30, 2018
How to Show Instructions to the User in Lightning Component
this Post Explains the How to Show the Instructions to User in Lightning Component
Using <ui:message /> Lighting tag We can Show The Different Severity to the user.
severity="confirm"
severity="info"
severity="warning"
severity="error"
Based on Your Requirement You Can Use the Severity
I used severity="info", For Showing the Instructions to The User.
Check Below Code For Reference
Screen Shot
Let Us Know If You have any queries.
Happy Learning!!
Using <ui:message /> Lighting tag We can Show The Different Severity to the user.
severity="confirm"
severity="info"
severity="warning"
severity="error"
Based on Your Requirement You Can Use the Severity
I used severity="info", For Showing the Instructions to The User.
Check Below Code For Reference
<ui:message severity="info" closable="false">
<h1 style="color:red;">Instructions:</h1>
<p>
<li>Please Enter Valid <b style="color:#5041f4">Opportunity Name and Close Date</b> to Search.</li>
<li>If you want to create New Opportunity Click on <b style="color:#5041f4">New</b> button.</li>
<li>If you want to Delete Mulitiple Records in a table. Please Select the Check boxs
for that record after that click on Delete Selected Button.</li>
<li>If you Want to Perform Row Action, Please Click On <b style="color:#5041f4">Down arrow on Table Row to Perform Row Actios(Edit, Delete,View).</b></li>
</p>
</ui:message>
Screen Shot
Let Us Know If You have any queries.
Happy Learning!!
Thursday, June 28, 2018
Monday, June 25, 2018
How To Display Records Data Based On Enter Value Using Lightning Component and SOSL Query(Account, Contact, Opportunity)
In This Example, we Used Account, Contact, Opportunity and filter the Data based on Account Name, we display the contact, Opportunity Data based Account Name.
Apex Class
Apex Class
public class AdvancedLtngWrks {
@AuraEnabled
Public static WraperForStorage getSearchRelated(String searchName){
WraperForStorage wrperObj = new WraperForStorage();
if(searchName != null && searchName != ' ') {
// builiding the SOSL Query
String searchQuery = 'FIND \'' + searchName + '\' RETURNING Account(Id,Name,Type), Contact(Id,Name,Account.Name where Account.Name =:searchName),Opportunity(Id,Name,Account.Name where Account.Name =:searchName)';
list<list<Sobject>> totalResults = search.query(searchQuery);
Account[] accList = (Account[])totalResults[0];
Contact[] conList = (Contact[])totalResults[1];
Opportunity[] oppList = (Opportunity[])totalResults[2];
wrperObj.acntsLst = accList;
wrperObj.cntsLst = conList;
wrperObj.OpportunitysLst = oppList;
}
return wrperObj;
}
Public class WraperForStorage{
@AuraEnabled Public List<Account> acntsLst {get;set;}
@AuraEnabled Public List<Contact> cntsLst {get;set;}
@AuraEnabled Public List<Opportunity> OpportunitysLst {get;set;}
Public WraperForStorage(){}
}
}
Lightning Component<aura:component controller="AdvancedLtngWrks" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
<aura:attribute name="searchName" type="String" />
<aura:attribute name="acntsList" type="Account[]" />
<aura:attribute name="contsList" type="Contact[]" />
<aura:attribute name="OpportunityList" type="Opportunity[]" />
<aura:attribute name="wrapperList" type="object"/>
<div class="slds-theme_default" >
<div class="slds-card slds-p-around--large">
<lightning:input type="search" label="Please Enter Account Name" name="search" value="{!v.searchName}" required="true" placeholder="SearchInAll" onkeyup="{!c.searchResult}"/>
</div>
<aura:if isTrue="{!v.wrapperList.acntsLst.length > 0}">
<div class="slds-card">
<div class="slds-text-heading_medium">
<strong>Search Result Based On Acount Name</strong>
</div>
<lightning:accordion >
<lightning:accordionSection name="Accounts" label="Accounts">
<aura:set attribute="body">
<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" title="Id">Id</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Name">Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Type">Type</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.wrapperList.acntsLst}" var="con">
<tr>
<th scope="row">
<div class="slds-truncate" title="{#con.Id}">{#con.Id}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{#con.Name}">{#con.Name}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{#con.Type}">{#con.Type}</div>
</th>
</tr>
</aura:iteration>
</tbody>
</table>
</aura:set>
</lightning:accordionSection>
<!-- second section -->
<lightning:accordionSection name="Contacts" label="Contacts">
<aura:set attribute="body">
<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" title="Id">Id</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Name">Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="AccountName">AccountName</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.wrapperList.cntsLst}" var="con">
<tr>
<th scope="row">
<div class="slds-truncate" title="{#con.Id}">{#con.Id}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{#con.Name}">{#con.Name}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{#con.Account.Name}">{#con.Account.Name}</div>
</th>
</tr>
</aura:iteration>
</tbody>
</table>
</aura:set>
</lightning:accordionSection>
<!-- 3rd section -->
<lightning:accordionSection name="Opportunitys" label="Opportunitys">
<aura:set attribute="body">
<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" title="Id">Id</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Name">Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="AccountName">AccountName</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.wrapperList.OpportunitysLst}" var="con">
<tr>
<th scope="row">
<div class="slds-truncate" title="{#con.Id}">{#con.Id}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{#con.Name}">{#con.Name}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{#con.Account.Name}">{#con.Account.Name}</div>
</th>
</tr>
</aura:iteration>
</tbody>
</table>
</aura:set>
</lightning:accordionSection>
</lightning:accordion>
</div>
</aura:if>
</div>
</aura:component>
JavaScript Controller
({
searchResult: function(component, event, helper) {
var action = component.get("c.getSearchRelated");
action.setParams({
"searchName": component.get("v.searchName")
});
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var res = response.getReturnValue();
component.set("v.wrapperList", res);
}
});
$A.enqueueAction(action);
}
})
Please Let Us Know If You have any Queries.
Happy Learning!!!!
Labels:
Apex,
Lightning,
Lightning Components,
SOSL
Subscribe to:
Posts (Atom)