Showing posts with label Utilities. Show all posts
Showing posts with label Utilities. Show all posts

Wednesday, June 17, 2026

LWC: Debug Log Viewer

📋 Debug Log Viewer for Salesforce LWC

View, filter, search, download, and manage Apex Debug Logs directly from Lightning Experience without opening Salesforce Setup.

📖 Project Overview

Debug Log Viewer is a reusable Salesforce Lightning Web Component that reads ApexLog records through the Salesforce Tooling API and displays them directly inside Lightning Experience.

Developers and administrators can inspect logs, search log contents, filter by event types, download log files, copy log content, and even bulk delete logs without navigating to Setup.

The solution uses Lightning Web Components, Apex, Tooling API integration, and Named Credentials to provide a modern debugging experience.

Debug Log Viewer Architecture

✨ Key Features

Feature Description
Debug Log Listing View ApexLog records in a Lightning datatable.
Filter Panel Filter by User Id, Operation, and Status.
Pagination Load logs incrementally in batches.
Log Detail Viewer Display full log content inside a dark-theme modal.
Category Filters Filter USER_DEBUG, SOQL, DML, and other log events.
Search Within Logs Quickly find keywords inside large log files.
Copy to Clipboard Copy raw or filtered log output.
Download Logs Save logs locally as .log files.
Bulk Delete Delete multiple Apex logs simultaneously.
Toast Notifications Success and error feedback for all operations.

🏗 Architecture

Lightning App / Utility Bar
│
├── debugLogViewer (Parent)
│
├── debugLogFilter (Child)
│
└── debugLogDetail (Child)
        │
        ▼
DebugLogViewerController.cls
        │
        ▼
Named Credential
        │
        ▼
Salesforce Tooling API
        │
        ├── ApexLog Query
        ├── Log Body Retrieval
        └── Bulk Delete Operations

📁 Project Structure

debug-log-viewer
│
├── force-app
│   └── main
│       └── default
│
├── lwc
│   ├── debugLogViewer
│   ├── debugLogFilter
│   └── debugLogDetail
│
├── classes
│   ├── DebugLogViewerController.cls
│   └── DebugLogViewerControllerTest.cls
│
├── namedCredentials
│   └── SalesforceToolingAPI
│
├── permissionsets
│   └── DebugLogViewer
│
└── README.md

⚙️ Core Components

Component Purpose
debugLogViewer Main orchestration component.
debugLogFilter Filtering UI for logs.
debugLogDetail Displays log body and search results.

🔎 Supported Filtering Options

  • User Id
  • Operation Name
  • Status
  • Date Sorting
  • Event Type Categories
  • Keyword Search

💻 Example Tooling API Query

SELECT Id,
       LogUser.Name,
       Operation,
       Status,
       DurationMilliseconds,
       LogLength,
       StartTime
FROM ApexLog
ORDER BY StartTime DESC
LIMIT 50

📂 Log Event Categories

USER_DEBUG
SOQL_EXECUTE_BEGIN
SOQL_EXECUTE_END
DML_BEGIN
DML_END
METHOD_ENTRY
METHOD_EXIT
EXCEPTION_THROWN

🚀 Deployment

sf org login web \
--instance-url https://test.salesforce.com

sf project deploy start \
--source-dir force-app

🔐 Prerequisites

  • Salesforce CLI (sf)
  • API Version 59+
  • Sandbox or Developer Edition Org
  • Connected App
  • Named Credential
  • Tooling API Access

🎯 Benefits

  • No need to open Salesforce Setup.
  • Faster debugging workflow.
  • Centralized log management.
  • Bulk deletion support.
  • Developer-friendly user experience.
  • Modern Lightning UI.

📌 Conclusion

Debug Log Viewer modernizes the Salesforce debugging experience by bringing Apex log management directly into Lightning Experience. With filtering, searching, downloading, and bulk management capabilities, it significantly improves developer productivity and reduces dependency on Setup-based tools.

Saturday, June 13, 2026

LWC: Apex Error Boundary

Apex Error Boundary

Centralized error handling pattern for Lightning Web Components with retry support, error categorization, and consistent user experience.

📖 Project Overview

Apex Error Boundary is a reusable Lightning Web Component pattern designed to centralize client-side error handling across Salesforce applications.

Instead of implementing duplicate error handling logic in every component, child LWCs simply dispatch a standard apexerror event when a wire adapter, imperative Apex call, or server operation fails.

The boundary component captures the error, categorizes it, displays a user-friendly UI, and optionally allows retrying failed operations.

Apex Error Boundary

✨ Key Features

Feature Description
Centralized Error Handling Single component handles all Apex and Wire errors.
Reusable Architecture Drop into any Salesforce project.
Retry Support Allow users to retry failed operations.
Technical Details Mode Optional expandable debugging information.
Error Categorization Converts raw Salesforce errors into user-friendly messages.
Event Driven Uses custom events for loose coupling.

🏗 Architecture Overview

Parent Page
│
└── c-apex-error-boundary
        │
        ▼
    Child Components
        │
        ├── @wire calls
        ├── Imperative Apex
        └── DML Operations
                │
                ▼
dispatchEvent('apexerror')
                │
                ▼
Boundary Captures Error
                │
                ▼
Error Classification
                │
                ▼
Friendly Error UI
                │
                ▼
Retry / Dismiss

📁 Repository Structure

apexErrorBoundary
│
├── classes
│   └── ExampleApexController.cls
│
├── lwc
│   ├── apexErrorBoundary
│   ├── apexErrorUtils
│   ├── exampleApexChild
│   └── accountRecordPage
│
├── staticresources
├── permissionsets
└── README.md

⚙️ Apex Controller Example

@AuraEnabled(cacheable=true)
public static Account getAccountDetails(Id accountId) {
    try {
        return [
            SELECT Id, Name, Industry
            FROM Account
            WHERE Id = :accountId
            LIMIT 1
        ];
    } catch (QueryException qe) {
        throw new AuraHandledException(
            'The account record could not be retrieved.'
        );
    }
}

💻 Boundary Component Highlights

@api customTitle;
@api fallbackMessage;
@api maxRetries = 3;
@api showTechnicalDetails = false;
@api allowDismiss = false;

@track showError = false;
@track showChild = true;
@track isRetrying = false;

🔄 Runtime Error Flow

  1. Child component executes Wire or Apex call.
  2. Failure occurs.
  3. Component dispatches apexerror event.
  4. Error Boundary intercepts event.
  5. Error is parsed and categorized.
  6. User-friendly error message is displayed.
  7. User can retry the operation.

🧩 Usage Example

<c-apex-error-boundary custom-title="Account Information" max-retries="3" show-technical-details="true">
<c-example-apex-child record-id="{recordId}">
</c-example-apex-child>
</c-apex-error-boundary>

📂 Error Categories

  • Validation Errors
  • DML Exceptions
  • SOQL Query Failures
  • Permission Errors
  • Network Errors
  • Unknown Exceptions

🚀 Benefits

  • Consistent UX across Salesforce applications.
  • Reduces duplicate error handling code.
  • Improves maintainability.
  • Simplifies debugging and support.
  • Provides enterprise-grade error management.

📦 Deployment

sf org login web -a myOrg

sf project deploy start \
--source-dir force-app \
-o myOrg

📌 Conclusion

Apex Error Boundary provides a robust, reusable, and scalable solution for handling Salesforce Apex and Wire errors in Lightning Web Components. By centralizing error management, teams can improve user experience, reduce duplicate code, and simplify long-term maintenance.

Thursday, June 11, 2026

LWC: Salesforce Field Set Renderer

Salesforce Field Set Renderer

Dynamically render Salesforce Field Sets in Lightning Web Components without hardcoding field names.

📖 Overview

Field Set Renderer is a reusable Salesforce Lightning Web Component that reads a named Field Set through Apex and dynamically renders fields at runtime. This approach eliminates hardcoded field references and allows administrators to control the UI simply by updating the Field Set configuration.

Salesforce Field Set Renderer

✨ Features

Feature Description
Zero Hardcoded Fields Field list is driven entirely by Field Set metadata.
View & Edit Modes Supports both lightning-record-view-form and lightning-record-edit-form.
FLS Aware Automatically respects field-level security permissions.
Required Validation Supports Field Set required and database required fields.
Configurable Layout Supports one-column and two-column layouts.
Lightning App Builder Ready Fully configurable through App Builder properties.

🏗 Architecture

FieldSetService.cls
        │
        ▼
Reads FieldSet Metadata
        │
        ▼
fieldSetRenderer (Reusable LWC)
        │
        ▼
View Mode / Edit Mode
        │
        ▼
Dynamic Salesforce Record Forms

📁 Project Structure

salesforce-fieldset-renderer
│
├── force-app
│   └── main
│       └── default
│           ├── classes
│           │   ├── FieldSetService.cls
│           │   └── FieldSetServiceTest.cls
│           │
│           └── lwc
│               ├── fieldSetRenderer
│               └── fieldSetRendererDemo
│
├── README.md
└── sfdx-project.json

⚙️ Apex Service Example

public with sharing class FieldSetService {

    public class FieldSetField {
        @AuraEnabled public String label;
        @AuraEnabled public String apiName;
        @AuraEnabled public String fieldType;
        @AuraEnabled public Boolean required;
        @AuraEnabled public Boolean editable;
    }

    @AuraEnabled(cacheable=true)
    public static List<FieldSetField> getFieldSetFields(
        String objectApiName,
        String fieldSetName
    ) {
        // Reads FieldSet metadata dynamically
    }
}

💻 LWC Usage Example

<c-field-set-renderer
    record-id={recordId}
    object-api-name="Contact"
    field-set-name="Contact_Overview"
    mode="view"
    columns="2"
    onrecordsave={handleSave}
    oncancel={handleCancel}>
</c-field-set-renderer>

🎯 Public API

Property Description
recordId Salesforce record Id.
objectApiName API name of SObject.
fieldSetName Developer name of Field Set.
mode View or Edit mode.
columns 1 or 2 column layout.

🚀 Deployment

sf org login web -a myOrg

sf project deploy start \
--source-dir force-app \
-o myOrg

🔒 Security & Permissions

  • Uses with sharing to respect record-level security.
  • Respects Field-Level Security (FLS).
  • Editable fields are automatically determined using Salesforce permissions.
  • Supports required field enforcement.

✅ Benefits

  • Reduces maintenance effort.
  • Admin-controlled UI configuration.
  • Reusable across multiple Salesforce objects.
  • Improves scalability and flexibility.
  • Ideal for dynamic forms and metadata-driven applications.

📌 Conclusion

Salesforce Field Set Renderer is a powerful reusable Lightning Web Component that dynamically renders fields based on Field Set metadata. By eliminating hardcoded field references, it enables administrators to manage layouts without code changes while maintaining security, flexibility, and scalability.

Wednesday, June 10, 2026

LWC: Export & Import Multiple Custom Setting Records

LWC: Export & Import Multiple Custom Setting Records

LWC: Export & Import Multiple Custom Setting Records

This project demonstrates how to export and import multiple Custom Setting records in Salesforce using Lightning Web Components (LWC) and Apex integration.


Export & Import Multiple Custom Setting Records

✨ Features

  • Export Custom Setting records to CSV
  • Import records using file upload
  • Apex-based backend processing
  • Lightning Web Component UI
  • Reusable architecture

📁 Project Structure


Export-ImportMultipleCustomSettingRecordsUsingLWC/
│
├── force-app/
│   └── main/
│       └── default/
│           ├── classes/
│           └── lwc/
│
├── README.md
└── sfdx-project.json
    

⚙️ Apex Controller


public with sharing class ExportCustomSettingController {

    @AuraEnabled(cacheable=true)
    public static List getCustomSettings() {
        return new List{'Setting A', 'Setting B'};
    }

    @AuraEnabled
    public static String processFile(String fileContent) {
        // Logic to parse CSV and insert records
        return 'File processed successfully';
    }
}
    

💻 LWC Component

HTML


<template>
    <lightning-card title="Custom Settings Export/Import">
        <lightning-button label="Export" onclick={handleExport}></lightning-button>
        <lightning-button label="Import" onclick={handleImport}></lightning-button>
    </lightning-card>
</template>
    

JavaScript


import { LightningElement } from 'lwc';

export default class CustomSetting extends LightningElement {

    handleExport() {
        console.log('Export triggered');
    }

    handleImport() {
        console.log('Import triggered');
    }
}
    


📌 Conclusion

This project helps Salesforce developers understand how to handle bulk data export/import using Lightning Web Components and Apex. It can be extended for Custom Metadata, Objects, or API integrations.