Use Case:
We have a requirement where we have a custom Page or an Application where we cannot see the standard Favorites button and we need to add the records to favorite list may be to visit it later. To meet this we can build our own button and an Object to meet the requirements to add the records as favorites.
Approach:
We need to configure Custom Object as below.
Object :- Add Favourites
API Name :- Add_Favourites__c
Now let us create a simple Lightning Component to display records from different objects. We will also add a button to it to add the record as Favorite.
This is the controller class to fetch the records as needed.Here we have created a simple Wrapper Class to store and return the records in Json format.
addToFavorites is a parent component to see the list of records.
addToFavourites.html
In the JS file as soon as this component loads we are fetching and displaying the records on UI. We are using Imperative method to fetch records.
API Name :- Add_Favourites__c
FIELDS |
Type |
API Name |
Favourites |
Formula (Text)
HYPERLINK("/"& Object_RecordId__c , Object_Record_Name__c) |
Favourites__c |
Object Name |
Text |
Object_Name__c |
Object Record Name |
Text |
Object_Record_Name__c |
Object RecordId |
Text |
Object_RecordId__c |
This is the controller class to fetch the records as needed.Here we have created a simple Wrapper Class to store and return the records in Json format.
AddToFavouritesController.cls
public class AddToFavouritesController {
public AddToFavouritesController() {
}
public class RecordWrapper {
@AuraEnabled
public List<Contact> contactList { get; set; }
@AuraEnabled
public List<Account> accountList { get; set; }
@AuraEnabled
public List<Opportunity> oppList { get; set; }
}
@AuraEnabled
public static String fetchRecords(){
try {
RecordWrapper recWrap = new RecordWrapper();
List<Contact> contactList = new List<Contact>();
contactList = [Select id,Name,Phone from Contact Order By Name DESC LIMIT 10 ];
recWrap.contactList = contactList;
List<Account> accountList = new List<Account>();
accountList = [Select id,Name,Phone from Account Order By Name LIMIT 10];
recWrap.accountList = accountList;
List<Opportunity> oppList = new List<Opportunity>();
oppList = [Select id,Name from Opportunity Order By Name LIMIT 10];
recWrap.oppList = oppList;
System.debug('recWrap '+recWrap );
return JSON.serialize(recWrap);
} catch (Exception ex) {
return JSON.serialize(ex);
}
}
@AuraEnabled
public static String addTofavourite(String recorIdVal, String recordName )
{
String objectName = '';
String keyPrefix = recorIdVal.substring(0,3);
for( Schema.SObjectType obj : Schema.getGlobalDescribe().Values() ){
String prefix = obj.getDescribe().getKeyPrefix();
if(prefix == keyPrefix){
objectName = obj.getDescribe().getName();
break;
}
}
List<Add_Favourites__c> addfavRecords= new List<Add_Favourites__c>();
addfavRecords = [Select id,Object_RecordId__c FROM Add_Favourites__c WHERE Object_RecordId__c =:recorIdVal] ;
Add_Favourites__c addfav = new Add_Favourites__c();
List<Add_Favourites__c> addfavlist = new List<Add_Favourites__c>();
System.debug('addfavRecords '+addfavRecords);
if (addfavRecords.isEmpty() ){
addfav.Object_Name__c = objectName ;
addfav.Object_Record_Name__c = recordName ;
addfav.Object_RecordId__c = recorIdVal;
addfavlist.add(addfav);
insert addfavlist;
return addfavlist[0].id ;
}
else{
delete addfavRecords ;
return 'Record Removed from Favourites';
}
}
}
addToFavorites is a parent component to see the list of records.
addToFavourites.html
<template>
<lightning-layout class="slds-m-right_medium">
<lightning-layout-item class="slds-m-right_small" size="4">
<div class="slds-p-around_small slds-page-header slds-page-header_object-home">
<p class="slds-text-title_caps slds-line-height_reset">Contacts</p>
</div>
<div>
<template for:each={contactList} for:item="item">
<div class="slds-p-around_small" key={item.Id}>
<c-record-tile record={item} onaddfav={addTofav}></c-record-tile>
</div>
</template>
</div>
</lightning-layout-item>
<lightning-layout-item class="slds-m-right_small" size="4">
<div class="slds-p-around_small slds-page-header slds-page-header_object-home">
<p class="slds-text-title_caps slds-line-height_reset">Accounts</p>
</div>
<div>
<template for:each={accountList} for:item="item">
<div class="slds-p-around_small" key={item.Id}>
<c-record-tile record={item} onaddfav={addTofav}></c-record-tile>
</div>
</template>
</div>
</lightning-layout-item>
<lightning-layout-item class="slds-m-right_small" size="4">
<div class="slds-p-around_small slds-page-header slds-page-header_object-home">
<p class="slds-text-title_caps slds-line-height_reset">Opportunity</p>
</div>
<div>
<template for:each={oppList} for:item="item">
<div class="slds-p-around_small" key={item.Id}>
<c-record-tile record={item} onaddfav={addTofav}></c-record-tile>
</div>
</template>
</div>
</lightning-layout-item>
</lightning-layout>
</template>
In the JS file as soon as this component loads we are fetching and displaying the records on UI. We are using Imperative method to fetch records.
addToFavourites.js
import { LightningElement } from 'lwc';
import fetchRecords from '@salesforce/apex/AddToFavouritesController.fetchRecords';
import addTofavourite from '@salesforce/apex/AddToFavouritesController.addTofavourite';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class AddToFavourites extends LightningElement {
contactList;
accountList;
oppList;
error;
connectedCallback(){
this.fetchRecords();
}
fetchRecords() {
fetchRecords()
.then(data => {
const wrapper = JSON.parse(data);
if(wrapper){
this.contactList = wrapper.contactList;
this.accountList = wrapper.accountList;
this.oppList = wrapper.oppList;
this.error = undefined ;
}
})
.catch(error => {
this.contactList = undefined;
this.accountList = undefined;
this.oppList = undefined;
console.log(error);
});
}
addTofav(event){
const recorIdVal = event.detail.recordId;
const recordName = event.detail.recordName;
addTofavourite({
recorIdVal : recorIdVal,
recordName : recordName,
})
.then(data => {
console.log(' Add To Fav ', data);
if(data == 'Record Removed from Favourites'){
const toast = new ShowToastEvent({
'title' : 'Success',
"message" : recordName + ' Removed from Favourites',
"variant" : "Success",
});
this.dispatchEvent(toast);
}else{
const toast = new ShowToastEvent({
'title' : 'Success',
"message" : recordName +' Added To Favourites!',
"variant" : "success",
});
this.dispatchEvent(toast);
}
})
.catch(error => {
console.log(error);
const toast = new ShowToastEvent({
'title' : 'Error!!',
"message" : JSON.stringify(error),
"variant" : "error",
});
this.dispatchEvent(toast);
});
}
}
addToFavourites.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Add To Favorites</masterLabel>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
This is recordTile component. A child component to display each record. In this component we have a handleChange method to handle add functionality. We will fire an event and handle it out in parent component addToFavourites.html
recordTile.html
recordTile.js
recordTile.css
recordTile.js-meta.xml
Actual Output:
We can also add a new DataTable Component on the same page see the List of Favorites records at the same time or as per the different use case.
Thanks for reading . :)
#HappyCoding
<template> <template if:true={record}> <lightning-card variant="Narrow" title={record.Name} icon-name="standard:story"> <div slot="actions"> <div> <div title="Add to Favorites" onclick={handleChange} class={buttonColor} style="height: 20px;width: 20px;border: 1px solid black;margin-right : 5px; "></div> <span class="slds-assistive-text">Add to Favorites</span> </div> </div> <div slot="footer"> <lightning-button variant="base" label="Details" title="View Details" onclick={handleClick} class="slds-m-left_x-small"> </lightning-button> </div> <p class="slds-p-horizontal_small"> {record.Name} </p> </lightning-card> </template> <template if:false={record}> No Records available to show here. </template> </template> |
recordTile.js
|
recordTile.css
.bgcolor
{
background-color: red;
color:red;
}
.btcolor{
background-color: white;
color:white;
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>
Thanks for reading . :)
#HappyCoding
Comments
Post a Comment