Boost Productivity with a Personalized Favorite Account List LWC

Introduction

Salesforce is a powerful CRM platform that enables businesses to manage their customer relationships effectively. However, as the number of accounts grows, it becomes increasingly challenging to locate and access specific accounts quickly. In this blog post, we will explore the importance of having a favorite account list in Salesforce and how it can significantly streamline your experience and boost productivity.

Why custom LWC?

This custom LWC provides ability to filter the favorite account list based on specific criteria, such as record types, any other filter. Unlike the standard account list, which typically displays all object, this LWC favorite account list allows for customization and filtering options. This ensures that you can narrow down the list to display only the accounts that meet certain criteria, enhancing the relevancy and usefulness of the list.

The standard account list in Salesforce usually includes all objects, which can be overwhelming when dealing with a large number of accounts. However, with the favorite account list feature, you have the flexibility to filter the displayed accounts based on your specific needs. For example, you can filter the list to show only accounts with a particular record type or accounts that meet certain criteria defined by your organization.

📺 DEMO

The Significance of a Favorite Account List

A favorite account list feature allows users to mark specific accounts as favorites, creating a personalized and easily accessible list of accounts that are of particular interest or relevance. Here are some key reasons why having a favorite account list is important:

  1. Quick Access to Important Accounts:
    In a large database of accounts, it can be time-consuming to search for specific accounts repeatedly. With a favorite account list, you can easily access your most important accounts without the need for extensive searching. This feature saves valuable time and ensures that you can quickly find and work with the accounts that matter the most to your business.
  2. Enhanced Productivity:
    By providing a streamlined and organized view of your favorite accounts, this feature boosts productivity. Instead of sifting through numerous accounts or relying on search queries, you can access your favorite accounts directly from the list. This convenience enables you to focus on critical tasks and engage with your key accounts efficiently.
  3. Personalization and Customization:
    Every user has unique preferences and requirements when it comes to account management. A favorite account list allows each user to tailor their experience by selecting the accounts that are relevant to their specific role or responsibilities. This personalization fosters a sense of ownership and empowers users to work with their preferred subset of accounts.
  4. Better Relationship Management:
    Managing customer relationships is at the core of Salesforce’s purpose. By having a favorite account list, you can proactively engage with key accounts, track their activities, and provide timely support. This feature ensures that you stay connected with your most important customers, leading to stronger relationships and better customer satisfaction.

Implementing the Favorite Account List

Now, let’s dive into the code provided in this blog post, which demonstrates a simple implementation of a favorite account list using Salesforce’s Lightning Web Components (LWC) and Apex.

The code utilizes various Salesforce APIs and techniques, such as the @wire decorator for server-side Apex calls, the NavigationMixin for navigating to account details, and the refreshApex function for updating the account list.

<template>
<div class="slds-page-header">
<div class="slds-page-header__row">
<div class="slds-page-header__col-title">
<div class="slds-media">
<div class="slds-media__figure">
<lightning-icon icon-name="standard:account"></lightning-icon>
</div>
<div class="slds-media__body">
<h1 class="slds-page-header__title slds-truncate" title="My Subscribed Accounts">My Favorites Accounts</h1>
</div>
</div>
</div>
<div class="slds-page-header__col-actions">
<template if:false={isLoading}>
<lightning-button-icon icon-name="utility:refresh" alternative-text="Refresh" title="Refresh" variant="bare" onclick={handleRefresh}></lightning-button-icon>
</template>
</div>
</div>
</div>
<div class="container">
<template if:true={isLoading}>
<lightning-spinner alternative-text="Loading" size="small"></lightning-spinner>
</template>
<template if:true={accounts}>
<ul class="slds-m-around_medium fancy-list">
<template for:each={accounts} for:item="account" for:index="index">
<li key={account.Id} data-id={account.Id} class="fancy-item">
<a href="javascript:void(0);" onclick={handleAccountClick} data-id={account.Id} target="_blank">{account.Name}</a>
<lightning-button-icon icon-name="utility:delete" alternative-text="Remove" title="Remove from favorites" variant="bare" data-id={account.Id} onclick={handleRemoveClick} class="remove-button"></lightning-button-icon>
</li>
</template>
</ul>
</template>
<template if:false={accounts}>
<div class="slds-p-around_medium">No subscribed accounts found.</div>
</template>
</div>
</template>
.fancy-list {
list-style-type: none;
padding: 0;
}
.slds-page-header{
border-bottom: none !important;
border-radius: 0px !important;
}
.container{
border: 1px solid rgb(201, 201, 201);
}
.fancy-item {
background-color: #f5f5f5;
border-radius: 5px;
padding: 10px;
margin-bottom: 10px;
display: flex;
justify-content: space-between;
align-items: center;
transition: background-color 0.3s;
}
.fancy-item:hover {
background-color: #f0f0f0;
}
.remove-button {
color: #f44336;
padding: 0;
margin-left: 10px;
height: 24px;
width: 24px;
}

The HTML and CSS sections of the code focus on the visual presentation of the favorite account list. The CSS styles create an attractive and intuitive design, making it easy to identify and interact with favorite accounts.

import { LightningElement, wire } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getSubscribedAccounts from '@salesforce/apex/AccountController.getSubscribedAccounts';
import removeAccountSubscription from '@salesforce/apex/AccountController.removeAccountSubscription';
import { refreshApex } from '@salesforce/apex';
export default class SubscribedAccountsList extends NavigationMixin(LightningElement) {
accounts = [];
wiredAccountsResult;
isLoading = false;
@wire(getSubscribedAccounts)
wiredSubscribedAccounts(result) {
this.wiredAccountsResult = result;
if (result.data) {
this.accounts = result.data;
} else if (result.error) {
console.error('Error retrieving subscribed accounts:', result.error);
}
}
handleRefresh() {
this.isLoading = true; // Show the spinner
refreshApex(this.wiredAccountsResult)
.finally(() => {
this.isLoading = false; // Hide the spinner
});
}
handleAccountClick(event) {
const accountId = event.target.dataset.id;
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: accountId,
objectApiName: 'Account',
actionName: 'view'
}
});
}
handleRemoveClick(event) {
const accountId = event.target.dataset.id;
removeAccountSubscription({ accountId })
.then(result => {
if (result) {
this.accounts = this.accounts.filter(account => account.Id !== accountId);
localStorage.setItem('subscribedAccounts', JSON.stringify(this.accounts));
this.showToast('Success', 'Account subscription removed.', 'success');
} else {
this.showToast('Error', 'Failed to remove account subscription.', 'error');
}
})
.catch(error => {
console.error('Error removing account subscription:', error);
this.showToast('Error', 'Failed to remove account subscription.', 'error');
});
}
showToast(title, message, variant) {
const event = new ShowToastEvent({
title: title,
message: message,
variant: variant
});
this.dispatchEvent(event);
}
}

The JavaScript code handles the core functionality, including retrieving and displaying the favorite accounts, refreshing the list, navigating to account details, and removing accounts from favorites. It leverages Apex methods to interact with the Salesforce database and perform operations such as retrieving subscribed accounts and removing account subscriptions.

public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getSubscribedAccounts() {
List<Account> subscribedAccounts = new List<Account>();
Set<Id> accountIds = new Set<Id>();
List<EntitySubscription> subscriptions = [
SELECT ParentId
FROM EntitySubscription
WHERE SubscriberId = :UserInfo.getUserId()
];
Set<Id> accountRecordTypeIds = new Set<Id>();
for (EntitySubscription subscription : subscriptions) {
if (subscription.ParentId.getSObjectType() == Account.sObjectType) {
accountIds.add(subscription.ParentId);
accountRecordTypeIds.add(subscription.ParentId);
}
}
if (!accountRecordTypeIds.isEmpty()) {
subscribedAccounts = [
SELECT Id, Name
FROM Account
WHERE Id IN :accountRecordTypeIds
];
}
return subscribedAccounts;
}
@AuraEnabled
public static Boolean removeAccountSubscription(Id accountId) {
try {
List<EntitySubscription> subscriptions = [
SELECT Id
FROM EntitySubscription
WHERE SubscriberId = :UserInfo.getUserId()
AND ParentId = :accountId
AND Parent.Type = 'Account'
];
if (!subscriptions.isEmpty()) {
delete subscriptions;
return true;
}
} catch (Exception ex) {
System.debug('Error removing account subscription: ' + ex.getMessage());
}
return false;
}
}

Let’s break down the key components of the Apex code:

  1. getSubscribedAccounts() Method:
    This method is annotated with @AuraEnabled(cacheable=true) to make it accessible from the Lightning web component. It retrieves a list of subscribed accounts associated with the current user.
  • It first initializes an empty <strong>List<Account></strong> called subscribedAccounts.
  • It creates a Set<Id> called accountIds to store the IDs of the subscribed accounts.
  • It queries the <strong>EntitySubscription</strong> object to retrieve the parent IDs (account IDs) associated with the current user.
  • It iterates through the retrieved subscriptions, adds the account IDs to the accountIds set, and checks if the parent object is of type Account.
  • If there are account record types to consider, it executes another query to fetch the subscribed accounts that match the specified record types.
  • Finally, it returns the <strong>subscribedAccounts</strong> list.
  1. <strong>removeAccountSubscription(Id accountId)</strong> Method:
    This method is annotated with @AuraEnabled to make it accessible from the Lightning web component. It removes the account subscription for a given account ID.
  • It attempts to delete the <strong>EntitySubscription</strong> record associated with the current user, the provided account ID, and the parent type ‘Account’.
  • If the deletion is successful, it returns true; otherwise, it returns false.
  • Any exceptions thrown during the deletion process are caught, and an error message is printed to the debug log.

These Apex methods interact with Salesforce’s data model to retrieve subscribed accounts and remove account subscriptions. They leverage SOQL queries and DML operations to retrieve and manipulate data efficiently.

In the Lightning web component’s JavaScript code, these Apex methods are called to retrieve subscribed accounts and remove accounts from the favorite list. The retrieved account data is then used to populate the favorite account list in the user interface.

It’s important to note that the provided code is a simple implementation that serves as a starting point. You have the flexibility to enhance and customize it according to your specific requirements. For example, you can incorporate pagination functionality to handle large lists of accounts efficiently. Additionally, you can extend the code to include sorting options, additional filters, or any other features that align with your business needs. You can also build the component for other objects like Contact, Opportunity, etc.

Conclusion

In conclusion, implementing a favorite account list in Salesforce can significantly enhance your user experience and productivity. This feature enables quick access to important accounts, improves relationship management, and provides personalization and customization options. By leveraging the provided code as a starting point, you can tailor the implementation to meet your specific requirements and preferences.

Remember, this code is a simplified version, and you can extend it further by adding pagination, sorting, or additional filtering options. The key is to create a favorite account list that aligns with your unique business needs and empowers you to work efficiently within the Salesforce ecosystem.

With a favorite account list in place, you’ll be equipped to navigate your Salesforce accounts effortlessly, stay focused on the accounts that matter, and cultivate strong customer relationships.

About the blog

SFDCLessons is a blog where you can find various Salesforce tutorials and tips that we have written to help beginners and experienced developers alike. we also share my experience and knowledge on Salesforce best practices, troubleshooting, and optimization. Don’t forget to follow us on:

Newsletter

Subscribe to our email newsletter to be notified when a new post is published.

Advertisements
Advertisements

Arun Kumar

Arun Kumar is a Salesforce Certified Platform Developer I with over 7+ years of experience working on the Salesforce platform. He specializes in developing custom applications, integrations, and reports to help customers streamline their business processes. Arun is passionate about helping businesses leverage the power of Salesforce to achieve their goals.

Leave a Reply