Transforming and Accessing Costs with DataTransformer
Our company, XYZ Corporation, recently integrated with a third-party vendor for managing product costs.
As part of this integration, there is a need to efficiently retrieve product costs based on their unique product codes.
The external system provides costs in a different format than our Salesforce custom object Product__c
.
To address this requirement, we implemented a DataTransformer class, aiming to transform the data from our internal Salesforce format to the format expected by the external system.
public with sharing class FSRK_DataTransformer {
public Map externalFormatMap;
// Constructor to initialize the map and perform data transformation
public FSRK_DataTransformer() {
externalFormatMap = new Map();
transformData();
}
// Private method to populate the map with product codes and costs
private void transformData() {
List productList = [SELECT ProductCode__c, Cost__c FROM FSRK_Product__c];
for (FSRK_Product__c product : productList) {
externalFormatMap.put(product.ProductCode__c, product.Cost__c);
}
}
// Public method to get cost by product code
public Decimal getCostByProductCode(String productCode) {
// Check if the product code exists in the map
if (externalFormatMap.containsKey(productCode)) {
return externalFormatMap.get(productCode);
} else {
// Handle the case where the product code is not found
throw new ProductCodeNotFoundException('Product code not found: ' + productCode);
}
}
// Custom exception class for handling product code not found scenario
public class ProductCodeNotFoundException extends Exception {}
}
In this DataTransformer class:
-
The
transformData
method populates the map during the class instantiation with product codes as keys and their corresponding costs. -
The
getCostByProductCode
method allows fetching the cost for a given product code. If the product code is not found, a custom exception (ProductCodeNotFoundException
) is thrown to handle this scenario.
This class provides a structured and efficient way to transform and retrieve product cost data, demonstrating the power and convenience of using maps in the Salesforce Apex environment.
DataTransformer Demo Script
public with sharing class FSRK_DataTransformerDemo {
public static void main() {
// Instantiate the DataTransformer
FSRK_DataTransformer dataTransformer = new FSRK_DataTransformer();
// Simulate products with associated costs
// In a real scenario, these products might be retrieved from Salesforce records
List products = new List{
new FSRK_Product__c(ProductCode__c='P001', Cost__c=50.00),
new FSRK_Product__c(ProductCode__c='P002', Cost__c=75.00),
new FSRK_Product__c(ProductCode__c='P003', Cost__c=100.00)
};
// Populate the externalFormatMap in the DataTransformer
for (FSRK_Product__c product : products) {
dataTransformer.externalFormatMap.put(product.ProductCode__c, product.Cost__c);
}
// Retrieve the cost for a specific product code
String productCodeToRetrieve = 'P002';
Decimal retrievedCost = dataTransformer.getCostByProductCode(productCodeToRetrieve);
// Display the retrieved cost
System.debug('Cost for Product Code ' + productCodeToRetrieve + ': $' + retrievedCost);
}
}
This script showcases how the DataTransformer class can be used to efficiently transform and retrieve costs for specific product codes.
Maximizing Salesforce Reporting
Our company, XYZ Corporation, manages a sales process where opportunities are associated with specific accounts. To gain insights into the overall performance of each account, there is a need to aggregate data from related opportunities. To address this requirement, we have implemented an AccountDataAggregator class. The goal is to aggregate and organize opportunity data for each account in a structured manner.
Why Use Maps
The decision to use maps in this scenario is driven by their ability to efficiently associate related opportunities with their corresponding accounts. Using maps allows us to create a direct link between account IDs and lists of associated opportunities, providing a convenient way to access and manipulate this aggregated data. The map structure simplifies the process of data aggregation, making the AccountDataAggregator class a powerful tool for analyzing account performance.
public with sharing class FSRK_AccountDataAggregator {
public Map<Id, List<Opportunity>> accountOpportunityMap;
// Constructor to initialize the map and perform data aggregation
public FSRK_AccountDataAggregator() {
accountOpportunityMap = new Map<Id, List<Opportunity>>();
aggregateData();
}
// Private method to populate the map with account IDs and associated opportunities
private void aggregateData() {
List<Opportunity> opportunityList = [SELECT Id, AccountId, Name, Amount FROM Opportunity];
for (Opportunity opp : opportunityList) {
if (!accountOpportunityMap.containsKey(opp.AccountId)) {
accountOpportunityMap.put(opp.AccountId, new List<Opportunity>());
}
accountOpportunityMap.get(opp.AccountId).add(opp);
}
}
// Public method to get opportunities by account ID
public List<Opportunity> getOpportunitiesByAccountId(Id accountId) {
// Check if the account ID exists in the map
if (accountOpportunityMap.containsKey(accountId)) {
return accountOpportunityMap.get(accountId);
} else {
// Handle the case where the account ID is not found
throw new AccountIdNotFoundException('Account ID not found: ' + accountId);
}
}
// Custom exception class for handling account ID not found scenario
public class AccountIdNotFoundException extends Exception {}
}
In this AccountDataAggregator class:
-
The
aggregateData
method populates the map during the class instantiation with account IDs as keys and lists of associated opportunities as values. -
The
getOpportunitiesByAccountId
method allows fetching opportunities for a given account ID. If the account ID is not found, a custom exception (AccountIdNotFoundException
) is thrown to handle this scenario.
AccountDataAggregator Demo Script
public with sharing class FSRK_DataAggregatorDemo {
public static void main() {
// Instantiate the DataAggregator
FSRK_AccountDataAggregator dataAggregator = new FSRK_AccountDataAggregator();
// Simulate opportunities associated with accounts
// In a real scenario, these opportunities might be retrieved from Salesforce records
List<Opportunity> opportunitiesForAccount1 = new List<Opportunity>{
new Opportunity(Name='Opportunity 1', Amount=5000),
new Opportunity(Name='Opportunity 2', Amount=8000)
};
List<Opportunity> opportunitiesForAccount2 = new List<Opportunity>{
new Opportunity(Name='Opportunity 3', Amount=10000),
new Opportunity(Name='Opportunity 4', Amount=12000)
};
// Associate opportunities with accounts in the DataAggregator
dataAggregator.accountOpportunityMap.put('001XXXXXXXXXXXXXXX', opportunitiesForAccount1);
dataAggregator.accountOpportunityMap.put('002YYYYYYYYYYYYYYY', opportunitiesForAccount2);
// Retrieve opportunities for a specific account
Id accountIdToRetrieve = '001XXXXXXXXXXXXXXX';
List<Opportunity> retrievedOpportunities = dataAggregator.getOpportunitiesByAccountId(accountIdToRetrieve);
// Display the retrieved opportunities
System.debug('Opportunities for Account ' + accountIdToRetrieve + ': ' + retrievedOpportunities);
}
}
This script showcases how the AccountDataAggregator class can be used to efficiently aggregate and retrieve opportunities associated with accounts.
Crafting Dynamic Queries with QueryBuilder
Our Salesforce application needs to support dynamic queries based on user input for advanced searches. To achieve this, we will create a QueryBuilder class that allows users to specify various search criteria dynamically. Maps will be utilized to store the query parameters and construct dynamic SOQL queries efficiently.
Why Use Maps
Maps provide a flexible way to store key-value pairs, making them ideal for dynamic query building. In this scenario, the map will store user-defined query parameters, allowing us to dynamically construct SOQL queries based on the provided criteria.
public with sharing class FSRK_QueryBuilder {
public Map<String, String> queryMap;
// Constructor to initialize the map and populate query parameters
public FSRK_QueryBuilder() {
queryMap = new Map<String, String>();
populateQueryParameters();
}
// Private method to populate the map with query parameters
private void populateQueryParameters() {
// Assume user input or some other mechanism to define query parameters
queryMap.put('Name', 'Test');
queryMap.put('Stage', 'Closed Won');
queryMap.put('Amount', '10000');
// Add more query parameters as needed
}
// Public method to dynamically build SOQL queries based on the map
public String buildDynamicQuery() {
String soqlQuery = 'SELECT Id, Name, Stage, Amount FROM Opportunity WHERE ';
// Iterate through the map and add conditions to the query
for (String field : queryMap.keySet()) {
soqlQuery += field + ' = \'' + queryMap.get(field) + '\' AND ';
}
// Remove the trailing ' AND ' from the query
soqlQuery = soqlQuery.removeEnd(' AND ');
return soqlQuery;
}
}
In this QueryBuilder class:
- The
populateQueryParameters
method simulates user-defined query parameters. In a real-world scenario, these parameters might come from user input or another source. -
The
buildDynamicQuery
method dynamically constructs a SOQL query based on the key-value pairs in the map. It iterates through the map, adding conditions to the query for each parameter.
This class provides a dynamic and efficient way to build SOQL queries based on user-defined criteria, showcasing the versatility of using maps in Salesforce Apex.
QueryBuilder Demo Script
public with sharing class FSRK_QueryBuilderDemo {
public static void main() {
// Instantiate the QueryBuilder
FSRK_QueryBuilder queryBuilder = new FSRK_QueryBuilder();
// Simulate user-defined query parameters
// In a real scenario, these might come from user input or another source
queryBuilder.queryMap.put('Name', 'Test');
queryBuilder.queryMap.put('Stage', 'Closed Won');
queryBuilder.queryMap.put('Amount', '10000');
// Build dynamic SOQL query
String dynamicQuery = queryBuilder.buildDynamicQuery();
// Display the dynamic SOQL query
System.debug('Dynamic SOQL Query: ' + dynamicQuery);
// Execute the dynamic query (this is a simulation, and you might execute it differently in a real scenario)
List<Opportunity> results = Database.query(dynamicQuery);
// Display the results (this is a simulation, and you might handle the results differently in a real scenario)
System.debug('Query Results: ' + results);
}
}
This script showcases how the QueryBuilder class can be used to dynamically construct and execute SOQL queries based on user-defined criteria.