Start tracking your progress
Trailhead Home
Trailhead Home

Build Admin Tools for Automated Configuration Changes

Learning Objectives

After completing this unit, you’ll be able to:
  • Describe how Apex Metadata API can simplify the configuration process.
  • Use Apex Metadata API to automate configuration changes.

Automate Repetitive Tasks for Your Admins

We’ve seen how to use Apex Metadata API to add a custom field to the page layouts in all our orgs using a post install script. Now let’s consider a different situation. Let’s say you’ve created a custom metadata type that must be configured and deployed into your org. Apex Metadata API lets you work with records of custom metadata types from within Apex. You can easily build a custom setup UI to enable your admins to configure and deploy your new custom metadata type using Apex.

For example, let’s say you’ve created a custom metadata type that represents a value-added tax (VAT) rate. You are required to configure the tax rate differently for each country you support. With Apex Metadata API, you can create your own setup UI to simplify the configuration process for your admins. One possible solution is to create a Visualforce page that lets admins configure the values in one place. The page uses Apex Metadata API to deploy your custom metadata type records into your org. Let’s dive into the details.

Note

Note

Note: This example is intentionally simple, so that we can focus on the basics of the process. In a more realistic example, the Visualforce page we create can be part of a setup wizard. The wizard can guide admins through a series of pages to do more complicated configuration. But by understanding the simpler case, you are prepared to tackle more complicated scenarios.

Add a New Custom Metadata Type

The first step is to create our custom metadata type. We create the type in Setup, although, as you saw in the last unit, you can also do this programmatically using Apex Metadata API.

  1. From Setup, enter Custom Metadata Types and click Custom Metadata Types.
  2. Click New Custom Metadata Type.
  3. Enter VAT Rate for the Label, with a Plural Label of VAT Rates, and click Save.

After you save, you land on the VAT Rate detail page, where you can add custom fields. We need two custom fields for our custom metadata type: Click New to create a field with the type Percent and the label Rate, and a field with the type Checkbox and the label Default. You can leave the rest of the default options.

Create VAT Rate Records

Now let’s create some records of our new custom metadata type.

  1. From the VAT Rate detail page, click Manage VAT Rates, then click New.
  2. Enter US for the Label, then click Save & New and add VAT rates for the following countries:
    1. UK
    2. SE
    3. IT
    4. RO

The values for the custom fields of these records don’t matter too much at this point. Admins configure the values from the Visualforce page, and the records are updated programmatically via Apex.

Build a Visualforce Page and Controller

Next, create an Apex controller class that uses the Apex Metadata API. The constructor for the class creates a list of VAT Rate values, which we collect with a Visualforce page. The save method retrieves the corresponding metadata for our records, and updates the values with the ones we’ve collected. Finally, the new metadata values are added to our deployment container and queued for deployment into the org.

  1. In the Developer Console, click File | New | Apex Class.
  2. Name the class VATController, then click OK.
  3. Get rid of any existing code, and copy and paste the following example code in its place.
public class VATController {
    
    public final List<VAT_Rate__mdt> VATs {get;set;}
    final Map<String, VAT_Rate__mdt> VATsByApiName {get; set;}
    
    public VATController() { 
        VATs = new List<VAT_Rate__mdt>();
        VATsByApiName = new Map<String, Vat_Rate__mdt>();
        for (VAT_Rate__mdt v : [SELECT QualifiedApiName, MasterLabel, Default__c, Rate__c
                                FROM VAT_Rate__mdt]) { 
                                    VATs.add(v);
                                    VATsByApiName.put(v.QualifiedApiName, v);
                                }
    }
    
    public PageReference save() {        
        
        // Create a metadata container.
        Metadata.DeployContainer container = new Metadata.DeployContainer();
        List<String> vatFullNames = new List<String>();
        for (String recordName : VATsByApiName.keySet()) {
            vatFullNames.add('VAT_Rate.' + recordName);
        }
        
        List<Metadata.Metadata> records = 
            Metadata.Operations.retrieve(Metadata.MetadataType.CustomMetadata, 
                                         vatFullNames);
        
        for (Metadata.Metadata record : records) {
            Metadata.CustomMetadata vatRecord = (Metadata.CustomMetadata) record;
            String vatRecordName = vatRecord.fullName.substringAfter('.');
            VAT_Rate__mdt vatToCopy = VATsByApiName.get(vatRecordName);
            
            for (Metadata.CustomMetadataValue vatRecValue : vatRecord.values) {
                vatRecValue.value = vatToCopy.get(vatRecValue.field);
            }
            
            // Add record to the container.
            container.addMetadata(vatRecord);
        }   
        
        // Deploy the container with the new components. 
        Id asyncResultId = Metadata.Operations.enqueueDeployment(container, null);
        
        return null;
    }
}

Next, we build a Visualforce page that lets admins configure the VAT rates for all five countries.

  1. Open the Developer Console by clicking the Setup gear, then Developer Console.
  2. In the Developer Console, click File | New | Visualforce Page.
  3. Name the page VATRateForm and click OK.
  4. Get rid of any existing code, and copy and paste the following example code in its place.
<apex:page controller="VATController">
    <apex:form >
        <apex:pageBlock title="VAT Rates" mode="edit">
            <apex:pageMessages />
            
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageBlockButtons>
            
            <apex:pageBlockTable value="{!VATs}" var="v">
                <apex:column value="{!v.MasterLabel}"/>
                <apex:column headerValue="Rate">
                    <apex:inputText value="{!v.Rate__c}"/>
                </apex:column>
                <apex:column headerValue="Default">
                    <apex:inputCheckbox value="{!v.Default__c}"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

You’ve created an Apex controller and a Visualforce page to collect and deploy metadata values. The next step is to test your deployment.

Resources

retargeting