Examples
Apex Custom Metadata
Querying Custom Metadata
Apex custom metadata query retrieves app settings with SOQL.
Understanding Custom Metadata in Apex
Custom Metadata in Salesforce is a powerful feature that allows developers to define application configurations that can be deployed from one organization to another. Unlike custom settings, custom metadata records are metadata themselves and can be packaged and deployed as part of the application.
Custom metadata types allow you to create your own setup objects whose records are metadata rather than data. This means you can build reusable, configurable apps and features that can be customized per the needs of your users.
Why Use Custom Metadata?
Custom metadata is beneficial for:
- Ease of Deployment: As metadata, they can be deployed via packages.
- Configurable Applications: Easily customize app behavior without code changes.
- Performance: Efficiently accessed via SOQL, making it faster than querying custom objects.
Querying Custom Metadata with SOQL
To retrieve custom metadata records in Apex, you utilize SOQL (Salesforce Object Query Language). This allows you to query settings and configurations you have defined in your custom metadata types.
In the example above, MyCustomMetadata__mdt
is your custom metadata type. The query retrieves all records and their fields, such as Field1__c
and Field2__c
.
Handling Custom Metadata in Apex
Once you have queried the custom metadata, you can manipulate it in your Apex code like any other data. This can be particularly useful for altering application behavior based on configuration settings without hardcoding values.
The loop in the example logs the values of Field1__c
and Field2__c
for each record, demonstrating how you might utilize these settings in your application logic.
Conclusion
Custom metadata in Apex provides a robust way to manage application settings and configurations. It ensures that your applications are both scalable and easy to maintain. By leveraging SOQL to query custom metadata, you can efficiently access and utilize your configuration data.
Examples
- Previous
- Platform Event
- Next
- Test Class