The force.com Platform provides us with features which are out of the box and helps increase productivity! Such is the “Metadata API”. Here, we will see how we can leverage the Metadata API and avoid doing tasks manually thus ultimately saving a lot of time!
What is Metadata API?
Launched back in the Summer’17 release the Apex Metadata API lets you make metadata changes directly from apex. We can use the handy features of apex in order to build custom setup UI scripts and perform automation actions behind the script. Let’s consider an example and see how it can help : Suppose you are an ISV and have created an app involving automation’s and many other features which are not generally available.You have packaged all your changes and is ready to be installed across org’s. Now, the admin team comes into picture for rolling out the changes. The admin team has to perform a lot of post installation steps manually using the setup UI over and over. This is where the metadata API comes in, you can create custom setup UI scripts to guide the admins through the process, and perform back end change actions using metadata api which updates the metadata while they go through the process over clicks and that’s it the changes will be available. Thus, avoiding repetitive steps.
Let’s look at few use cases where we can use the Metadata API:
- Using the Metadata API we can build tools which can automate configuration changes.
- We can update our metadata changes in multiple org’s by deploying it across multiple org’s from apex using the Metadata API Deploycallback class which uses a deployment container and executes based on actions specified.
- We can control multiple org metadata in a single org. And can perform CRUD operations.
There are lots of use cases around, let’s implement few and see how actually the Metadata API can help us increase productivity! In our example here we will be retrieving the metadata from the contact object. We will retrieve a section named ‘Additional Information’ from the page layout of contact, add a new field into that section all from apex!! Sounds Interesting ain’t that? Let’s check it out… [sourcecode language=”Java”] public class UpdateContactPageLayout { public Metadata.layout addLayoutItem(){ //Retreive metadata from the contact page layout using Metadata.Operations.retrieve method List Metadata.Metadata layoutsList = Metadata.Operations.retrieve(Metadata.MetadataType.Layout, new List String{‘Contact-Contact Layout’}); //Getting Layout from the contact object Metadata.Layout layoutMetadata = (Metadata.Layout) layoutsList.get(0); Metadata.LayoutSection contactLayoutSection = null; List Metadata.LayoutSection layoutSections = layoutMetadata.layoutSections; for (Metadata.LayoutSection section : layoutSections) { /** Assigning section value to contactLayoutSection Variable if section label satisfies condition **/ if (section.label == ‘Additional Information’) { contactLayoutSection = section; break; } } List Metadata.LayoutColumn contactColumns = contactLayoutSection.layoutColumns; List Metadata.LayoutItem contactLayoutItems = contactColumns.get(0).layoutItems; Metadata.LayoutItem newField = new Metadata.LayoutItem(); newField.behavior = Metadata.UiBehavior.Edit; newField.field = ‘AMAPI__Apex_MD_API_Twitter_name__c’; contactLayoutItems.add(newField); system.debug(‘newfield Inserted’); system.debug(‘contactLayoutItems’ + contactLayoutItems); system.debug(newField); return layoutMetadata; } } Let’s check out the logs and see whether a new field was created or not! If you are trying this out instead of “amapi” in the newField.field variable specify your org’s namespace followed by the field you want to create. E.g: ‘yourOrgNameSpace_Field_Name__c’
We can see that the field got created, but in order to finally add the field in your layout we need to deploy the Metadata changes using Deploy container. This will finally add your metadata to the page layout. Refer here for Deployment Container Class. Now, let’s quickly look at another example of creating a record in a Custom Metadata Type. In our case we have already created a Custom Metadata type called “Vat Rate”. And we will be creating a new record for the custom Metadata Type using Custom Metadata API from apex. If you are a newbie and have no idea how to create a custom metadata type refer this “Create Custom MetadataType“! Let’s look at the code: [sourcecode language=”Java”] public class MetadataExample { public void updateMetadata(){ //Retreive custom metadata type details from org Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata(); //insert the fullName and Label value for the record you want to create customMetadata.fullName = ‘VAT_Rate.NewRecordFromMetadataAPI’; customMetadata.label = ‘NewRecordFromMetadataAPI’; //We will populate the field called Rate in the Custom Metadata type with some value Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue(); customField.field = ‘Rate__c’; customField.value = 10; /**Adding record values to the customMetadata type ***/ customMetadata.values.add(customField); /** Deployment Container to deploy the metadata changes **/ Metadata.DeployContainer deployContainer = new Metadata.DeployContainer(); deployContainer.addMetadata(customMetadata); /** This will invoke the deployment Process of the changes **/ system.debug(‘customMetadata’+customMetadata); system.debug(‘Metadata deployed’); Id asyncResultId = Metadata.Operations.enqueueDeployment(deployContainer, null); } } Also, check the logs just to be sure there are no errors! 😀
You can track your metadata change deployment in the Deployment Status. Navigate to Setup –>In Quick Find type “Deployment Status” and click on the record initiated with proper timestamp details.
Once the changes are deployed, we will navigate to the Custom Metadata Type and check whether a record has been created or not. Let’s navigate to the Vat Rate Custom metadata type and see. Now let’s navigate to the record detail page and check whether the value of “rate” specified in code is populated or not. That’s it! We have created a metadata record type using the Metadata API from Apex and not manually!!
Advantages of using the Metadata API:
- You can deploy your metadata changes using deployable packages across multiple org’s without needing to create change sets and doing tasks manually.
- You can write custom scripts to perform backend actions for automating metadata changes across the org. thus eliminating a major heck of manually work for the SF admins out there!! Interesting? Ain’t that.
You can also create CustomMetadata types using the MetadataService class library. That shall be all for now! We will continue to dive deep on this in the next follow up blog and also check how to test your MetadataAPI and discuss possibilities of designing a solution for Bulk Creation of Custom Metadata Types and automate Metadata Changes. Thank you for reading!! Don’t be shy to try it out, and keep on blazing your trails!! 🙂Â