SlideShare a Scribd company logo
1 of 21
MDT Records
Deployments
Deploying custom metadata records from Apex Code
2018
Introduction
Bohdan Dovhan - Senior Salesforce Developer and Salesforce Development Team Lead
Salesforce Certified Development Lifecycle & Deployment Designer
Salesforce Certified Platform Developer I
Salesforce Certified Platform Developer II
Salesforce Certified Platform App Builder
8 years of Development experience
5 years of Development on Salesforce platform
Long-long time ago
Long-long time ago in far-far away galaxy there were developers working on a
very-very legacy project on an internal Salesforce customizations. Later that
client company was acquired by a bigger company and a new integration with a
new external system of a bigger company was requested to be established.
This integration involved configuration records of country and state codes in
external database. Implementation of another subsidiary company which was
also acquired by a bigger company and which also used Salesforce, used
custom objects to store those country and code mappings. However, custom
objects records are not deployable, so these configuration mappings cannot be
migrated from sandbox to production environment during deployment.
Decision was made to convert those records from Custom Object and Custom
Metadata and to delegate this task to Junior Developer.
Unknown feature
Discovery was made that developers are not aware of of custom metadata records
deployment feature and might assume that team lead expect them to convert
those 5000 records manually.
Since I was surprised that such feature is not known amongst Salesforce
Developers, I decided to prepare this talk. Since this feature was introduced
more than year and a half ago, I supposed that everyone knows about it which
apparently is not completely true statement.
Data Example
Org based development vs. source driven development.
In a traditional SF Dev Lifecycle, application builders use sandboxes to create and
test changes. Source of truth is either production or any sandbox containing
most recent version of code and customization.
With Salesforce DX, you might use source driven development using latest
versions from a centralized source control system like GIT or SVN.
Operations class
Salesforce Summer 17 release introduced Metadata namespace and
Operations class inside it with the following capabilities:
1. Retrieval and deployment of custom metadata records
2. Retrieval and deployment of layouts
Well to retrieve custom metadata records we could just use SOQL
Retrieval and deployments of layouts is only relevant to package developers.
The most important feature here is ability to deploy custom metadata records by
Apex code
Metadata Loader
Wait, can’t we just use standard salesforce Custom Metadata Record Uploader package page?
Yes, but you will have to deploy this package to your organization and prepare CSV file.
Still, this application uses Metadata API under the hood while it could use Metadata.Operations class.
Metadata API
Wait, can’t we just use Metadata API?
Yes, but in such case you will have to add your organization endpoint to remote site settings and to use
complex WSDL classes for a simple task.
Also you can use Andrew Fawcett library which also utilizes Metadata API.
Since Metadata.Operations class doesn’t support deletion of metadata records, if you need to delete
custom metadata records you would still use Metadata API or libraries based on it
Records deployment
Let’s assume there are some mappings stored in Custom Objects records or Custom Settings.
Then enqueueDeployment method of Metadata.Operations class can be leveraged to write a simple
and concise code to convert those records into Custom Metadata records and those metadata
records can be migrated using ANT Migration Tool.
Since in most cases you don’t need to delete custom metadata records, this is a perfect fit for this task.
In case if you need to delete custom metadata records you could either build destructiveChanges.xml
and delete them using ANT Migration Tool or leverage Metadata API.
Deployment may either create a new custom metadata record or update existing custom metadata
records, depending on the uniqueness of the fullName attribute. If there is a custom metadata
record with a given DeveloperName, then that particular record will be updated with new values
during deployment but if such a record doesn’t exist, then a new record will be created during the
deployment process.
Also, the label attribute is, in fact, required even though it is not populated in the example from
documentation. I spent some time trying to figure this out when I was attempting to deploy custom
metadata records by Apex code, for the very first time.
Fields population
In order to populate a custom field on a Custom Metadata record, CustomMetadataValue model should
be instantiated and then it should be added to custom metadata record values. However, to populate
standard field on a Custom Metadata record one has to populate the label and fullName attributes
directly on a Custom Metadata record. Label and fullName attributes correspond to MasterLabel
and DeveloperName standard fields even though their names differ.
private Metadata.CustomMetadata makeMDTRecord(Sobject r) {
Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata();
customMetadata.fullName = populateName( r );
customMetadata.label = populateLabel( r );
for (SObjectField key: this.mappings.keySet() ) {
Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
customField.field = String.valueOf(this.mappings.get(key) );
customField.value = r.get(key);
customMetadata.values.add(customField);
}
return customMetadata;
}
Update and Deploy
public Id updateAndDeployMetadata(List<SObject> sourceRecords, SObjectType dest,
Map<SObjectField, SObjectField> mappings, String fullNameDef, String labelDef
) {
Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
this.mappings = mappings;
this.destName = dest.getDescribe().getName();
this.fullNameParts = fullNameDef.split('+’);
this.labelParts = labelDef.split('+');
if( sourceRecords != null && !sourceRecords.isEmpty() ) {
this.fields = sourceRecords[0].getSObjectType().getDescribe().fields.getMap();
for (SObject r: sourceRecords ) {
mdContainer.addMetadata(makeMDTRecord(r));
}
return Metadata.Operations.enqueueDeployment(mdContainer, null);
}
return null;
}
Code Example
The final example of code for records conversion is following
new MD().updateAndDeployMetadata(
[ SELECT Field1__c, Field2__c, Field3__c, Field4__c FROM Object__c ],
CustomMetadata__mdt.sObjectType,
new Map<SObjectField, SObjectField>{
Object__c.Field1__c=> CustomMetadata__mdt.Field1__c,
Object__c.Field2__c=> CustomMetadata__mdt.Field2__c,
Object__c.Field3__c=> CustomMetadata__mdt.Field3__c,
Object__c.Field4__c => CustomMetadata__mdt.Field4__c
},
'X+Field1__c+_+Field2__c’,
'Field3__c+ +Field4__c '
);
Metadata Relations
Also, when you need to populate a Custom Metadata relationship, you need to use DeveloperName
from the corresponding parent records instead of an identifier, which might seem odd since
everywhere else in Apex you either use Salesforce Id or External Id to populate relationships.
The same applies when you need to populate a Entity or Field relationship, the DeveloperName
from the corresponding Entity or Field should be used instead of Ids.
Undocumented limit
There are some undocumented limitations on a number of custom metadata records which can be
deployed by one call of a  enqueueDeployment method of Operations class. The actual number
depends on the data included in the custom metadata records, and in my case I was able to deploy
around 1,488 custom metadata records at one time while trying to insert or update 1,489 records
yielded from an Salesforce System UnexpectedException Error.
Splitting custom metadata records into chunks and invoking a enqueueDeployment method several
times helps to deal with the issue
Package developers
There is “Deploy Metadata from Non-Certified Package Versions via Apex” checkbox setting, which enables beta
packages to perform a custom metadata records deployment from Apex code. This checkbox can be
found in Setup  Build  Develop  Apex Settings menu in the setup configuration.
Package developers
So if you need to test the beta version of your developed managed package before passing a security
review, you will have to check this checkbox and save your settings on every organization where you
install a beta version of your package.
Metadata Relations
Metadata Relationships provide very convenient and useful way to dynamically store references to
SObjects and Fields. So you don’t need anymore to store
However, only some standard Objects are supported, so User object and User fields are not supported.
Conclusion
As we can conclude now, the ability to deploy customization data directly from Apex code is a really great
and astonishing feature which has been available since the version 40 of Salesforce API. We have
considered here several use cases where this might be needed. Sometimes this can be useful for
developing interface to deploy custom metadata records from user experience, or this can be much
more useful and beneficial if you ever need to convert your existing customization data, stored in
Custom Objects or Custom Settings, in order to be able to include them into deployment scripts.
References1.
https://help.salesforce.com/articleView?id=custommetadatatypes_dataloader.htm&type=5
2. https://corevalue.net/deploying-custom-metadata-records-apex-code/
3.
https://patlatus.wordpress.com/2018/10/18/convert-custom-object-records-to-custom-meta
4.
https://developer.salesforce.com/docs/atlas.en-us.208.0.apexcode.meta/apexcode/apex_c
5.
https://patlatus.wordpress.com/2017/05/12/most-wanted-salesforce-feature-ever-bye-bye-
6.
https://gist.githubusercontent.com/Patlatus/53ce49fde265c0aa3d0f2c3fdda8b900/raw/bb1
7.
https://gist.githubusercontent.com/Patlatus/bb4c964f72ddfb60bbd4710bb34597b9/raw/9c
References8. https://success.salesforce.com/ideaView?id=0873A000000cNVjQAM
9.

More Related Content

What's hot

Salesforce.com Org Migration Overview
Salesforce.com Org Migration OverviewSalesforce.com Org Migration Overview
Salesforce.com Org Migration OverviewShell Black
 
Cloud Operating Models for Accelerated Cloud Transformation - AWS Summit Sydney
Cloud Operating Models for Accelerated Cloud Transformation - AWS Summit SydneyCloud Operating Models for Accelerated Cloud Transformation - AWS Summit Sydney
Cloud Operating Models for Accelerated Cloud Transformation - AWS Summit SydneyAmazon Web Services
 
Make business buying easy with Salesforce Commerce Cloud
Make business buying easy with Salesforce Commerce CloudMake business buying easy with Salesforce Commerce Cloud
Make business buying easy with Salesforce Commerce CloudAtocloud
 
Salesforce Online Training
Salesforce Online TrainingSalesforce Online Training
Salesforce Online TrainingKeylabs
 
Salesforce Marketing Cloud Training | Salesforce Training For Beginners - Mar...
Salesforce Marketing Cloud Training | Salesforce Training For Beginners - Mar...Salesforce Marketing Cloud Training | Salesforce Training For Beginners - Mar...
Salesforce Marketing Cloud Training | Salesforce Training For Beginners - Mar...Edureka!
 
Hybridcloud & Multicloud with GCP Anthos.pptx
Hybridcloud & Multicloud with GCP Anthos.pptxHybridcloud & Multicloud with GCP Anthos.pptx
Hybridcloud & Multicloud with GCP Anthos.pptxHARSH MANVAR
 
Salesforce Training For Beginners | Salesforce Tutorial | Salesforce Training...
Salesforce Training For Beginners | Salesforce Tutorial | Salesforce Training...Salesforce Training For Beginners | Salesforce Tutorial | Salesforce Training...
Salesforce Training For Beginners | Salesforce Tutorial | Salesforce Training...Edureka!
 
Stanford Case Study - Salesforce.com Transformation
Stanford Case Study - Salesforce.com TransformationStanford Case Study - Salesforce.com Transformation
Stanford Case Study - Salesforce.com TransformationSteve Greene
 
The Art of Cloud Auditing - ISACA ID
The Art of Cloud Auditing - ISACA IDThe Art of Cloud Auditing - ISACA ID
The Art of Cloud Auditing - ISACA IDEryk Budi Pratama
 
15 Tips on Salesforce Data Migration - Naveen Gabrani & Jonathan Osgood
15 Tips on Salesforce Data Migration - Naveen Gabrani & Jonathan Osgood15 Tips on Salesforce Data Migration - Naveen Gabrani & Jonathan Osgood
15 Tips on Salesforce Data Migration - Naveen Gabrani & Jonathan OsgoodSalesforce Admins
 
What Is Salesforce? | Salesforce Training - What Does Salesforce Do? | Salesf...
What Is Salesforce? | Salesforce Training - What Does Salesforce Do? | Salesf...What Is Salesforce? | Salesforce Training - What Does Salesforce Do? | Salesf...
What Is Salesforce? | Salesforce Training - What Does Salesforce Do? | Salesf...Edureka!
 
What is Salesforce lighting explained
What is Salesforce lighting explainedWhat is Salesforce lighting explained
What is Salesforce lighting explainedRoy Gilad
 
The Transformation Journey with Cloud Technology
The Transformation Journey with Cloud TechnologyThe Transformation Journey with Cloud Technology
The Transformation Journey with Cloud TechnologyAmazon Web Services
 
Salesforce Advantage (8 Core Differentiators)
Salesforce Advantage (8 Core Differentiators)Salesforce Advantage (8 Core Differentiators)
Salesforce Advantage (8 Core Differentiators)Salesforce Partners
 
Migrate to Microsoft Azure with Confidence
Migrate to Microsoft Azure with ConfidenceMigrate to Microsoft Azure with Confidence
Migrate to Microsoft Azure with ConfidenceDavid J Rosenthal
 
Best Practices with Apex in 2022.pdf
Best Practices with Apex in 2022.pdfBest Practices with Apex in 2022.pdf
Best Practices with Apex in 2022.pdfMohith Shrivastava
 

What's hot (20)

Cloud Migration Strategy Framework
Cloud Migration Strategy FrameworkCloud Migration Strategy Framework
Cloud Migration Strategy Framework
 
Salesforce.com Org Migration Overview
Salesforce.com Org Migration OverviewSalesforce.com Org Migration Overview
Salesforce.com Org Migration Overview
 
Org Merge Best Practices
Org Merge Best PracticesOrg Merge Best Practices
Org Merge Best Practices
 
Cloud Operating Models for Accelerated Cloud Transformation - AWS Summit Sydney
Cloud Operating Models for Accelerated Cloud Transformation - AWS Summit SydneyCloud Operating Models for Accelerated Cloud Transformation - AWS Summit Sydney
Cloud Operating Models for Accelerated Cloud Transformation - AWS Summit Sydney
 
Make business buying easy with Salesforce Commerce Cloud
Make business buying easy with Salesforce Commerce CloudMake business buying easy with Salesforce Commerce Cloud
Make business buying easy with Salesforce Commerce Cloud
 
Salesforce Online Training
Salesforce Online TrainingSalesforce Online Training
Salesforce Online Training
 
Salesforce Marketing Cloud Training | Salesforce Training For Beginners - Mar...
Salesforce Marketing Cloud Training | Salesforce Training For Beginners - Mar...Salesforce Marketing Cloud Training | Salesforce Training For Beginners - Mar...
Salesforce Marketing Cloud Training | Salesforce Training For Beginners - Mar...
 
Hybridcloud & Multicloud with GCP Anthos.pptx
Hybridcloud & Multicloud with GCP Anthos.pptxHybridcloud & Multicloud with GCP Anthos.pptx
Hybridcloud & Multicloud with GCP Anthos.pptx
 
Salesforce Training For Beginners | Salesforce Tutorial | Salesforce Training...
Salesforce Training For Beginners | Salesforce Tutorial | Salesforce Training...Salesforce Training For Beginners | Salesforce Tutorial | Salesforce Training...
Salesforce Training For Beginners | Salesforce Tutorial | Salesforce Training...
 
Stanford Case Study - Salesforce.com Transformation
Stanford Case Study - Salesforce.com TransformationStanford Case Study - Salesforce.com Transformation
Stanford Case Study - Salesforce.com Transformation
 
The Art of Cloud Auditing - ISACA ID
The Art of Cloud Auditing - ISACA IDThe Art of Cloud Auditing - ISACA ID
The Art of Cloud Auditing - ISACA ID
 
Salesforce overview
Salesforce overviewSalesforce overview
Salesforce overview
 
15 Tips on Salesforce Data Migration - Naveen Gabrani & Jonathan Osgood
15 Tips on Salesforce Data Migration - Naveen Gabrani & Jonathan Osgood15 Tips on Salesforce Data Migration - Naveen Gabrani & Jonathan Osgood
15 Tips on Salesforce Data Migration - Naveen Gabrani & Jonathan Osgood
 
What Is Salesforce? | Salesforce Training - What Does Salesforce Do? | Salesf...
What Is Salesforce? | Salesforce Training - What Does Salesforce Do? | Salesf...What Is Salesforce? | Salesforce Training - What Does Salesforce Do? | Salesf...
What Is Salesforce? | Salesforce Training - What Does Salesforce Do? | Salesf...
 
Migration Planning
Migration PlanningMigration Planning
Migration Planning
 
What is Salesforce lighting explained
What is Salesforce lighting explainedWhat is Salesforce lighting explained
What is Salesforce lighting explained
 
The Transformation Journey with Cloud Technology
The Transformation Journey with Cloud TechnologyThe Transformation Journey with Cloud Technology
The Transformation Journey with Cloud Technology
 
Salesforce Advantage (8 Core Differentiators)
Salesforce Advantage (8 Core Differentiators)Salesforce Advantage (8 Core Differentiators)
Salesforce Advantage (8 Core Differentiators)
 
Migrate to Microsoft Azure with Confidence
Migrate to Microsoft Azure with ConfidenceMigrate to Microsoft Azure with Confidence
Migrate to Microsoft Azure with Confidence
 
Best Practices with Apex in 2022.pdf
Best Practices with Apex in 2022.pdfBest Practices with Apex in 2022.pdf
Best Practices with Apex in 2022.pdf
 

Similar to Custom Metadata Records Deployment From Apex Code

User and group security migration
User and group security migrationUser and group security migration
User and group security migrationAmit Sharma
 
Best practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APIBest practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APISanchit Dua
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migrationAmit Sharma
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utilityAmit Sharma
 
Best practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APIBest practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APISanchit Dua
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utilityAmit Sharma
 
Summer '16 Realease notes
Summer '16 Realease notesSummer '16 Realease notes
Summer '16 Realease notesaggopal1011
 
Schema-based multi-tenant architecture using Quarkus &amp; Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus &amp; Hibernate-ORM.pdfSchema-based multi-tenant architecture using Quarkus &amp; Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus &amp; Hibernate-ORM.pdfseo18
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentationOleksii Usyk
 
Compass Framework
Compass FrameworkCompass Framework
Compass FrameworkLukas Vlcek
 
Dot Net Fundamentals
Dot Net FundamentalsDot Net Fundamentals
Dot Net FundamentalsLiquidHub
 
Punta Dreaming by Luciano Straga #pd17 - Punta del Este, Uruguay
Punta Dreaming by Luciano Straga #pd17 - Punta del Este, UruguayPunta Dreaming by Luciano Straga #pd17 - Punta del Este, Uruguay
Punta Dreaming by Luciano Straga #pd17 - Punta del Este, UruguayLuciano Straga
 
Athena java dev guide
Athena java dev guideAthena java dev guide
Athena java dev guidedvdung
 
Learning To Run - XPages for Lotus Notes Client Developers
Learning To Run - XPages for Lotus Notes Client DevelopersLearning To Run - XPages for Lotus Notes Client Developers
Learning To Run - XPages for Lotus Notes Client DevelopersKathy Brown
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
Bhadale Group of Companies - digital projects
Bhadale Group of Companies - digital projectsBhadale Group of Companies - digital projects
Bhadale Group of Companies - digital projectsVijayananda Mohire
 
Informatica metadata exchange frequently asked questions by quontra solutions
Informatica metadata exchange frequently asked questions by quontra solutionsInformatica metadata exchange frequently asked questions by quontra solutions
Informatica metadata exchange frequently asked questions by quontra solutionsQuontra Solutions
 
Informatica Metadata Exchange Frequently Asked Questions by Quontra Solutions
Informatica Metadata Exchange Frequently Asked Questions by Quontra SolutionsInformatica Metadata Exchange Frequently Asked Questions by Quontra Solutions
Informatica Metadata Exchange Frequently Asked Questions by Quontra SolutionsQuontra Solutions
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
 

Similar to Custom Metadata Records Deployment From Apex Code (20)

User and group security migration
User and group security migrationUser and group security migration
User and group security migration
 
Best practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APIBest practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata API
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migration
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utility
 
Best practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata APIBest practices in using Salesforce Metadata API
Best practices in using Salesforce Metadata API
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utility
 
Summer '16 Realease notes
Summer '16 Realease notesSummer '16 Realease notes
Summer '16 Realease notes
 
Schema-based multi-tenant architecture using Quarkus &amp; Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus &amp; Hibernate-ORM.pdfSchema-based multi-tenant architecture using Quarkus &amp; Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus &amp; Hibernate-ORM.pdf
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Compass Framework
Compass FrameworkCompass Framework
Compass Framework
 
Dot Net Fundamentals
Dot Net FundamentalsDot Net Fundamentals
Dot Net Fundamentals
 
Punta Dreaming by Luciano Straga #pd17 - Punta del Este, Uruguay
Punta Dreaming by Luciano Straga #pd17 - Punta del Este, UruguayPunta Dreaming by Luciano Straga #pd17 - Punta del Este, Uruguay
Punta Dreaming by Luciano Straga #pd17 - Punta del Este, Uruguay
 
Athena java dev guide
Athena java dev guideAthena java dev guide
Athena java dev guide
 
Learning To Run - XPages for Lotus Notes Client Developers
Learning To Run - XPages for Lotus Notes Client DevelopersLearning To Run - XPages for Lotus Notes Client Developers
Learning To Run - XPages for Lotus Notes Client Developers
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Bhadale Group of Companies - digital projects
Bhadale Group of Companies - digital projectsBhadale Group of Companies - digital projects
Bhadale Group of Companies - digital projects
 
Informatica metadata exchange frequently asked questions by quontra solutions
Informatica metadata exchange frequently asked questions by quontra solutionsInformatica metadata exchange frequently asked questions by quontra solutions
Informatica metadata exchange frequently asked questions by quontra solutions
 
Informatica Metadata Exchange Frequently Asked Questions by Quontra Solutions
Informatica Metadata Exchange Frequently Asked Questions by Quontra SolutionsInformatica Metadata Exchange Frequently Asked Questions by Quontra Solutions
Informatica Metadata Exchange Frequently Asked Questions by Quontra Solutions
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 

More from Bohdan Dovhań

Second-generation managed packages
Second-generation managed packagesSecond-generation managed packages
Second-generation managed packagesBohdan Dovhań
 
Migrate To Lightning Web Components from Aura framework to increase performance
Migrate To Lightning Web Components from Aura framework to increase performance Migrate To Lightning Web Components from Aura framework to increase performance
Migrate To Lightning Web Components from Aura framework to increase performance Bohdan Dovhań
 
SFDX - Spring 2019 Update
SFDX - Spring 2019 UpdateSFDX - Spring 2019 Update
SFDX - Spring 2019 UpdateBohdan Dovhań
 
Salesforce Developer eXperience (SFDX)
Salesforce Developer eXperience (SFDX)Salesforce Developer eXperience (SFDX)
Salesforce Developer eXperience (SFDX)Bohdan Dovhań
 
Sdfc forbidden and advanced techniques
Sdfc forbidden and advanced techniquesSdfc forbidden and advanced techniques
Sdfc forbidden and advanced techniquesBohdan Dovhań
 
Being A Salesforce Jedi
Being A Salesforce JediBeing A Salesforce Jedi
Being A Salesforce JediBohdan Dovhań
 
Salesforce certifications process
Salesforce certifications processSalesforce certifications process
Salesforce certifications processBohdan Dovhań
 
Salesforce for marketing
Salesforce for marketingSalesforce for marketing
Salesforce for marketingBohdan Dovhań
 
Introduction about development, programs, saas and salesforce
Introduction about development, programs, saas and salesforceIntroduction about development, programs, saas and salesforce
Introduction about development, programs, saas and salesforceBohdan Dovhań
 

More from Bohdan Dovhań (13)

Second-generation managed packages
Second-generation managed packagesSecond-generation managed packages
Second-generation managed packages
 
Migrate To Lightning Web Components from Aura framework to increase performance
Migrate To Lightning Web Components from Aura framework to increase performance Migrate To Lightning Web Components from Aura framework to increase performance
Migrate To Lightning Web Components from Aura framework to increase performance
 
SFDX - Spring 2019 Update
SFDX - Spring 2019 UpdateSFDX - Spring 2019 Update
SFDX - Spring 2019 Update
 
Salesforce Developer eXperience (SFDX)
Salesforce Developer eXperience (SFDX)Salesforce Developer eXperience (SFDX)
Salesforce Developer eXperience (SFDX)
 
SFDX Presentation
SFDX PresentationSFDX Presentation
SFDX Presentation
 
Sdfc forbidden and advanced techniques
Sdfc forbidden and advanced techniquesSdfc forbidden and advanced techniques
Sdfc forbidden and advanced techniques
 
SFDC REST API
SFDC REST APISFDC REST API
SFDC REST API
 
Being A Salesforce Jedi
Being A Salesforce JediBeing A Salesforce Jedi
Being A Salesforce Jedi
 
Salesforce REST API
Salesforce  REST API Salesforce  REST API
Salesforce REST API
 
Salesforce certifications process
Salesforce certifications processSalesforce certifications process
Salesforce certifications process
 
Salesforce for marketing
Salesforce for marketingSalesforce for marketing
Salesforce for marketing
 
Introduction about development, programs, saas and salesforce
Introduction about development, programs, saas and salesforceIntroduction about development, programs, saas and salesforce
Introduction about development, programs, saas and salesforce
 
ExtJS Sencha Touch
ExtJS Sencha TouchExtJS Sencha Touch
ExtJS Sencha Touch
 

Recently uploaded

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Recently uploaded (20)

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 

Custom Metadata Records Deployment From Apex Code

  • 1. MDT Records Deployments Deploying custom metadata records from Apex Code 2018
  • 2. Introduction Bohdan Dovhan - Senior Salesforce Developer and Salesforce Development Team Lead Salesforce Certified Development Lifecycle & Deployment Designer Salesforce Certified Platform Developer I Salesforce Certified Platform Developer II Salesforce Certified Platform App Builder 8 years of Development experience 5 years of Development on Salesforce platform
  • 3. Long-long time ago Long-long time ago in far-far away galaxy there were developers working on a very-very legacy project on an internal Salesforce customizations. Later that client company was acquired by a bigger company and a new integration with a new external system of a bigger company was requested to be established. This integration involved configuration records of country and state codes in external database. Implementation of another subsidiary company which was also acquired by a bigger company and which also used Salesforce, used custom objects to store those country and code mappings. However, custom objects records are not deployable, so these configuration mappings cannot be migrated from sandbox to production environment during deployment. Decision was made to convert those records from Custom Object and Custom Metadata and to delegate this task to Junior Developer.
  • 4. Unknown feature Discovery was made that developers are not aware of of custom metadata records deployment feature and might assume that team lead expect them to convert those 5000 records manually. Since I was surprised that such feature is not known amongst Salesforce Developers, I decided to prepare this talk. Since this feature was introduced more than year and a half ago, I supposed that everyone knows about it which apparently is not completely true statement.
  • 5. Data Example Org based development vs. source driven development. In a traditional SF Dev Lifecycle, application builders use sandboxes to create and test changes. Source of truth is either production or any sandbox containing most recent version of code and customization. With Salesforce DX, you might use source driven development using latest versions from a centralized source control system like GIT or SVN.
  • 6. Operations class Salesforce Summer 17 release introduced Metadata namespace and Operations class inside it with the following capabilities: 1. Retrieval and deployment of custom metadata records 2. Retrieval and deployment of layouts Well to retrieve custom metadata records we could just use SOQL Retrieval and deployments of layouts is only relevant to package developers. The most important feature here is ability to deploy custom metadata records by Apex code
  • 7. Metadata Loader Wait, can’t we just use standard salesforce Custom Metadata Record Uploader package page? Yes, but you will have to deploy this package to your organization and prepare CSV file. Still, this application uses Metadata API under the hood while it could use Metadata.Operations class.
  • 8. Metadata API Wait, can’t we just use Metadata API? Yes, but in such case you will have to add your organization endpoint to remote site settings and to use complex WSDL classes for a simple task. Also you can use Andrew Fawcett library which also utilizes Metadata API. Since Metadata.Operations class doesn’t support deletion of metadata records, if you need to delete custom metadata records you would still use Metadata API or libraries based on it
  • 9. Records deployment Let’s assume there are some mappings stored in Custom Objects records or Custom Settings. Then enqueueDeployment method of Metadata.Operations class can be leveraged to write a simple and concise code to convert those records into Custom Metadata records and those metadata records can be migrated using ANT Migration Tool. Since in most cases you don’t need to delete custom metadata records, this is a perfect fit for this task. In case if you need to delete custom metadata records you could either build destructiveChanges.xml and delete them using ANT Migration Tool or leverage Metadata API. Deployment may either create a new custom metadata record or update existing custom metadata records, depending on the uniqueness of the fullName attribute. If there is a custom metadata record with a given DeveloperName, then that particular record will be updated with new values during deployment but if such a record doesn’t exist, then a new record will be created during the deployment process. Also, the label attribute is, in fact, required even though it is not populated in the example from documentation. I spent some time trying to figure this out when I was attempting to deploy custom metadata records by Apex code, for the very first time.
  • 10. Fields population In order to populate a custom field on a Custom Metadata record, CustomMetadataValue model should be instantiated and then it should be added to custom metadata record values. However, to populate standard field on a Custom Metadata record one has to populate the label and fullName attributes directly on a Custom Metadata record. Label and fullName attributes correspond to MasterLabel and DeveloperName standard fields even though their names differ. private Metadata.CustomMetadata makeMDTRecord(Sobject r) { Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata(); customMetadata.fullName = populateName( r ); customMetadata.label = populateLabel( r ); for (SObjectField key: this.mappings.keySet() ) { Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue(); customField.field = String.valueOf(this.mappings.get(key) ); customField.value = r.get(key); customMetadata.values.add(customField); } return customMetadata; }
  • 11. Update and Deploy public Id updateAndDeployMetadata(List<SObject> sourceRecords, SObjectType dest, Map<SObjectField, SObjectField> mappings, String fullNameDef, String labelDef ) { Metadata.DeployContainer mdContainer = new Metadata.DeployContainer(); this.mappings = mappings; this.destName = dest.getDescribe().getName(); this.fullNameParts = fullNameDef.split('+’); this.labelParts = labelDef.split('+'); if( sourceRecords != null && !sourceRecords.isEmpty() ) { this.fields = sourceRecords[0].getSObjectType().getDescribe().fields.getMap(); for (SObject r: sourceRecords ) { mdContainer.addMetadata(makeMDTRecord(r)); } return Metadata.Operations.enqueueDeployment(mdContainer, null); } return null; }
  • 12. Code Example The final example of code for records conversion is following new MD().updateAndDeployMetadata( [ SELECT Field1__c, Field2__c, Field3__c, Field4__c FROM Object__c ], CustomMetadata__mdt.sObjectType, new Map<SObjectField, SObjectField>{ Object__c.Field1__c=> CustomMetadata__mdt.Field1__c, Object__c.Field2__c=> CustomMetadata__mdt.Field2__c, Object__c.Field3__c=> CustomMetadata__mdt.Field3__c, Object__c.Field4__c => CustomMetadata__mdt.Field4__c }, 'X+Field1__c+_+Field2__c’, 'Field3__c+ +Field4__c ' );
  • 13. Metadata Relations Also, when you need to populate a Custom Metadata relationship, you need to use DeveloperName from the corresponding parent records instead of an identifier, which might seem odd since everywhere else in Apex you either use Salesforce Id or External Id to populate relationships. The same applies when you need to populate a Entity or Field relationship, the DeveloperName from the corresponding Entity or Field should be used instead of Ids.
  • 14. Undocumented limit There are some undocumented limitations on a number of custom metadata records which can be deployed by one call of a  enqueueDeployment method of Operations class. The actual number depends on the data included in the custom metadata records, and in my case I was able to deploy around 1,488 custom metadata records at one time while trying to insert or update 1,489 records yielded from an Salesforce System UnexpectedException Error. Splitting custom metadata records into chunks and invoking a enqueueDeployment method several times helps to deal with the issue
  • 15. Package developers There is “Deploy Metadata from Non-Certified Package Versions via Apex” checkbox setting, which enables beta packages to perform a custom metadata records deployment from Apex code. This checkbox can be found in Setup Build Develop Apex Settings menu in the setup configuration.
  • 16. Package developers So if you need to test the beta version of your developed managed package before passing a security review, you will have to check this checkbox and save your settings on every organization where you install a beta version of your package.
  • 17. Metadata Relations Metadata Relationships provide very convenient and useful way to dynamically store references to SObjects and Fields. So you don’t need anymore to store However, only some standard Objects are supported, so User object and User fields are not supported.
  • 18.
  • 19. Conclusion As we can conclude now, the ability to deploy customization data directly from Apex code is a really great and astonishing feature which has been available since the version 40 of Salesforce API. We have considered here several use cases where this might be needed. Sometimes this can be useful for developing interface to deploy custom metadata records from user experience, or this can be much more useful and beneficial if you ever need to convert your existing customization data, stored in Custom Objects or Custom Settings, in order to be able to include them into deployment scripts.