Introduction
Using SOQL with custom metadata in Apex classes can streamline your Salesforce development. It allows developers to store configuration data, making your code dynamic, reusable, and easier to maintain. In this post, we’ll explore the concept, use cases, and provide a practical SOQL Custom Metadata in Apex Class Example.
Read another blog about How SOQL Query Executes in System Mode.
Why Use Custom Metadata in Apex Classes?
Custom metadata allows developers to store static, app-specific data. You can retrieve it using SOQL queries, just like querying records in standard or custom objects. With custom metadata, your code becomes more dynamic and flexible, as you can adjust configurations without altering the Apex code itself.
Benefits of Using Custom Metadata:
- Dynamic Configurations: Easily change values without code modifications.
- Improved Maintainability: Reduce hard-coded values, which enhances readability.
- Consistency Across Org: Custom metadata values replicate easily across sandboxes and production.
Understanding SOQL and Custom Metadata in Salesforce
SOQL (Salesforce Object Query Language) is similar to SQL and lets you query Salesforce data. When used with custom metadata, SOQL helps retrieve configuration settings that guide the behavior of Apex classes without altering code.
Custom metadata records can include values such as API keys, URLs, business rules, or feature toggles. This approach keeps your data-driven logic separate from your code, supporting a clean codebase.
Setting Up Custom Metadata in Salesforce
Creating custom metadata in Salesforce is straightforward. Here’s how to set it up before writing an Apex class that utilizes it:
- Navigate to Setup: Go to Setup, then search for “Custom Metadata Types.”
- Create a New Custom Metadata Type: Define the type, such as “App Config,” and add fields for each setting you’ll need (e.g., “API_Endpoint,” “Timeout_Limit”).
- Add Metadata Records: Define values for each configuration. For example, you could have a metadata record for API settings, with fields like “Endpoint_URL” and “API_Key.”
Example: Using SOQL Custom Metadata in Apex Class
Let’s walk through a practical example of using SOQL with custom metadata in an Apex class. In this example, we’ll create an Apex class to pull custom metadata settings for an external API call configuration.
1. Create the Custom Metadata Type
First, create a metadata type named `API_Settings`. Add fields that store configuration details:
- Endpoint_URL (Text)
- API_Key (Text)
- Timeout_Limit (Number)
2. Add Metadata Records
Define a record with values:
- Endpoint_URL: “https://api.example.com/data”
- API_Key: “ABC123XYZ”
- Timeout_Limit: 30
3. Write the Apex Class Using SOQL to Access Custom Metadata
With custom metadata records in place, use SOQL in Apex to retrieve these settings. Here’s a sample Apex class demonstrating how to use SOQL to access custom metadata:
```apex
public class APIService {
private static final String API_TYPE = 'DataAPI';
public static String fetchData() {
// Retrieve the custom metadata record using SOQL
API_Settings__mdt settings = [SELECT Endpoint_URL__c, API_Key__c, Timeout_Limit__c
FROM API_Settings__mdt
WHERE DeveloperName = :API_TYPE
LIMIT 1];
// Use the retrieved metadata in your logic
String endpoint = settings.Endpoint_URL__c;
String apiKey = settings.API_Key__c;
Integer timeout = Integer.valueOf(settings.Timeout_Limit__c);
// Log the retrieved data (for debugging purposes)
System.debug('Endpoint URL: ' + endpoint);
System.debug('API Key: ' + apiKey);
System.debug('Timeout Limit: ' + timeout);
// Proceed with your API call logic using the above configurations
// Example: HTTP callout logic using endpoint, apiKey, and timeout
return 'Data fetched successfully.';
}
}
```
In this example:
- SOQL Query: The SOQL query retrieves the metadata record, enabling access to its fields (`Endpoint_URL`, `API_Key`, and `Timeout_Limit`).
- Dynamic Data Use: The metadata values drive the `fetchData` method’s behavior, making the API configuration flexible.
Benefits of Using SOQL Custom Metadata in Apex Classes
Implementing custom metadata in Apex classes offers multiple advantages:
- Simplified Code Changes: Custom metadata reduces hard-coded values. If the API endpoint changes, you can update the metadata instead of editing code.
- Easier Testing: Developers can create different metadata records in testing environments, allowing for more controlled testing.
- Dynamic Code Adjustments: With SOQL querying custom metadata, the same Apex class can adapt to various configurations without manual updates.
Advanced Use Cases for Custom Metadata with SOQL
Custom metadata, combined with SOQL, is not limited to API configurations. Here are more advanced use cases:
1. Feature Toggles
Use custom metadata to control feature access. For instance, store toggle flags in metadata and retrieve them in Apex classes to control access without redeploying code.
Example Code:
```apex
public class FeatureController {
public static Boolean isFeatureEnabled(String featureName) {
Feature_Toggle__mdt toggle = [SELECT IsEnabled__c
FROM Feature_Toggle__mdt
WHERE DeveloperName = :featureName
LIMIT 1];
return toggle. IsEnabled__c;
}
}
```
2. Business Rules and Discounts
Store business rules, such as discount rates or eligibility criteria, in custom metadata. Use SOQL to pull these settings dynamically, which allows business rule adjustments without altering code.
Example Code:
```apex
public class DiscountCalculator {
public static Decimal getDiscountRate(String accountType) {
Discount_Rules__mdt discount = [SELECT Discount_Rate__c
FROM Discount_Rules__mdt
WHERE Account_Type__c = :accountType
LIMIT 1];
return discount.Discount_Rate__c;
}
}
```
Best Practices for Using Custom Metadata with SOQL in Apex
While custom metadata provides flexibility, following best practices ensures optimal performance and maintainability:
- Limit SOQL Queries: Limit the number of custom metadata SOQL queries in your Apex code to avoid hitting governor limits.
- Use Custom Labels Sparingly: Only store relevant data that drives application behavior in custom metadata. Avoid storing large data sets.
- Version Control: Maintain version control for custom metadata types, especially when configurations vary across environments.
Limitations of Using SOQL with Custom Metadata
While custom metadata is powerful, it does come with a few limitations:
- Field Limitations: Custom metadata types are restricted to certain field types, such as Text, Number, and Checkbox. Fields like Picklist or Lookup are not supported.
- Limits on Record Creation: Salesforce places a limit on the number of custom metadata records. Plan your configurations carefully to stay within these limits.
- Read-Only: You cannot edit custom metadata from Apex; updates must be made through the Salesforce UI or metadata API.
Conclusion
Using SOQL custom metadata in Apex classes empowers Salesforce developers to build dynamic, adaptable applications. By following this approach, you can store critical configurations separately from your code, making updates easier and code more maintainable. Whether you need configuration settings, feature toggles, or business rules, custom metadata enhances flexibility without compromising efficiency.
Take advantage of the flexibility custom metadata offers to improve your Salesforce applications. With SOQL, you can retrieve and use custom metadata seamlessly, making your applications more robust, adaptable, and ready to scale.
By mastering SOQL custom metadata in Apex classes, Salesforce developers can unlock new possibilities for efficient and agile application management.