SlideShare a Scribd company logo
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.
Custom Metadata Records Deployment From Apex Code
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 (20)

Oral Medicine Slides (Final BDS)
Oral Medicine Slides (Final BDS)Oral Medicine Slides (Final BDS)
Oral Medicine Slides (Final BDS)
Cing Sian Dal
 
Enamel Erosion
Enamel ErosionEnamel Erosion
Enamel Erosion
fitango
 
natal neonatal teeth-pedo
 natal neonatal teeth-pedo natal neonatal teeth-pedo
natal neonatal teeth-pedo
Parth Thakkar
 
Tooth Injuries| Tooth Trauma| Treatment of Tooth Trauma
Tooth Injuries| Tooth Trauma| Treatment of Tooth TraumaTooth Injuries| Tooth Trauma| Treatment of Tooth Trauma
Tooth Injuries| Tooth Trauma| Treatment of Tooth Trauma
Dr. Rajat Sachdeva
 
Oper.ii 06
Oper.ii 06Oper.ii 06
Oper.ii 06
Lama K Banna
 
Measured boot for embedded devices
Measured boot for embedded devicesMeasured boot for embedded devices
Measured boot for embedded devices
Dmitry Baryshkov
 
anatomy of pulp cavity and access opening.pptx
anatomy of pulp cavity and access opening.pptxanatomy of pulp cavity and access opening.pptx
anatomy of pulp cavity and access opening.pptx
adityabhagat62
 
Deposits on the Teeth
Deposits on the TeethDeposits on the Teeth
Deposits on the Teeth
Dr. Blend Ahmed
 
Oral Hygiene Care and Aids
Oral Hygiene Care and AidsOral Hygiene Care and Aids
Oral Hygiene Care and Aids
KatieHenkel1
 
Operative Dentistry 3
Operative Dentistry 3Operative Dentistry 3
Operative Dentistry 3
MedicineAndFamily
 
Stainless steel crowns
Stainless steel crownsStainless steel crowns
Stainless steel crowns
princesoni3954
 
Recent Methodology in Management of Non-carious Lesions
Recent Methodology in Management of Non-carious LesionsRecent Methodology in Management of Non-carious Lesions
Recent Methodology in Management of Non-carious Lesions
AlaaDokmak
 
Complications of local anesthesia
Complications of local anesthesiaComplications of local anesthesia
Complications of local anesthesia
Nishant Kumar
 
Obturation of Root Canal - An Endodontic Overview
Obturation of Root Canal - An Endodontic OverviewObturation of Root Canal - An Endodontic Overview
Obturation of Root Canal - An Endodontic Overview
Iraqi Dental Academy
 
Root canal preparation techniques _ endodontic treatment
Root canal preparation techniques _ endodontic treatment Root canal preparation techniques _ endodontic treatment
Root canal preparation techniques _ endodontic treatment
Israa Awadh
 
Oral pigmentation lesion
Oral pigmentation lesionOral pigmentation lesion
Oral pigmentation lesion
shreegunjan21
 
Exodontia
ExodontiaExodontia
Exodontia
AbhijitSarkar175565
 
Pit and fissure sealant
Pit and fissure sealantPit and fissure sealant
Pit and fissure sealant
Saquib Shahab
 
Complications of exodontia
Complications of  exodontia Complications of  exodontia
Complications of exodontia
Dr. Prathamesh Fulsundar
 
Tips and ticks
Tips and ticksTips and ticks
Tips and ticks
NUHA ELKADIKI
 
Oral Medicine Slides (Final BDS)
Oral Medicine Slides (Final BDS)Oral Medicine Slides (Final BDS)
Oral Medicine Slides (Final BDS)
Cing Sian Dal
 
Enamel Erosion
Enamel ErosionEnamel Erosion
Enamel Erosion
fitango
 
natal neonatal teeth-pedo
 natal neonatal teeth-pedo natal neonatal teeth-pedo
natal neonatal teeth-pedo
Parth Thakkar
 
Tooth Injuries| Tooth Trauma| Treatment of Tooth Trauma
Tooth Injuries| Tooth Trauma| Treatment of Tooth TraumaTooth Injuries| Tooth Trauma| Treatment of Tooth Trauma
Tooth Injuries| Tooth Trauma| Treatment of Tooth Trauma
Dr. Rajat Sachdeva
 
Measured boot for embedded devices
Measured boot for embedded devicesMeasured boot for embedded devices
Measured boot for embedded devices
Dmitry Baryshkov
 
anatomy of pulp cavity and access opening.pptx
anatomy of pulp cavity and access opening.pptxanatomy of pulp cavity and access opening.pptx
anatomy of pulp cavity and access opening.pptx
adityabhagat62
 
Oral Hygiene Care and Aids
Oral Hygiene Care and AidsOral Hygiene Care and Aids
Oral Hygiene Care and Aids
KatieHenkel1
 
Stainless steel crowns
Stainless steel crownsStainless steel crowns
Stainless steel crowns
princesoni3954
 
Recent Methodology in Management of Non-carious Lesions
Recent Methodology in Management of Non-carious LesionsRecent Methodology in Management of Non-carious Lesions
Recent Methodology in Management of Non-carious Lesions
AlaaDokmak
 
Complications of local anesthesia
Complications of local anesthesiaComplications of local anesthesia
Complications of local anesthesia
Nishant Kumar
 
Obturation of Root Canal - An Endodontic Overview
Obturation of Root Canal - An Endodontic OverviewObturation of Root Canal - An Endodontic Overview
Obturation of Root Canal - An Endodontic Overview
Iraqi Dental Academy
 
Root canal preparation techniques _ endodontic treatment
Root canal preparation techniques _ endodontic treatment Root canal preparation techniques _ endodontic treatment
Root canal preparation techniques _ endodontic treatment
Israa Awadh
 
Oral pigmentation lesion
Oral pigmentation lesionOral pigmentation lesion
Oral pigmentation lesion
shreegunjan21
 
Pit and fissure sealant
Pit and fissure sealantPit and fissure sealant
Pit and fissure sealant
Saquib Shahab
 

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
Amit 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 API
Sanchit Dua
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migration
Amit Sharma
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utility
Amit 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 API
Sanchit Dua
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utility
Amit Sharma
 
Summer '16 Realease notes
Summer '16 Realease notesSummer '16 Realease notes
Summer '16 Realease notes
aggopal1011
 
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdfSchema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
seo18
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
Oleksii Usyk
 
Compass Framework
Compass FrameworkCompass Framework
Compass Framework
Lukas Vlcek
 
Dot Net Fundamentals
Dot Net FundamentalsDot Net Fundamentals
Dot Net Fundamentals
LiquidHub
 
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
Luciano Straga
 
Athena java dev guide
Athena java dev guideAthena java dev guide
Athena java dev guide
dvdung
 
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
Kathy 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 projects
Vijayananda 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 Solutions
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
Quontra Solutions
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
Make School
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migration
Amit 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 API
Sanchit Dua
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migration
Amit Sharma
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utility
Amit 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 API
Sanchit Dua
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utility
Amit Sharma
 
Summer '16 Realease notes
Summer '16 Realease notesSummer '16 Realease notes
Summer '16 Realease notes
aggopal1011
 
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdfSchema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
seo18
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
Oleksii Usyk
 
Compass Framework
Compass FrameworkCompass Framework
Compass Framework
Lukas Vlcek
 
Dot Net Fundamentals
Dot Net FundamentalsDot Net Fundamentals
Dot Net Fundamentals
LiquidHub
 
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
Luciano Straga
 
Athena java dev guide
Athena java dev guideAthena java dev guide
Athena java dev guide
dvdung
 
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
Kathy 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 projects
Vijayananda 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 Solutions
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
Quontra Solutions
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
Make School
 
Ad

More from Bohdan Dovhań (14)

PUBLISHING YOUR PACKAGE TO APPEXCHANGEIN 2023
PUBLISHING YOUR PACKAGE TO APPEXCHANGEIN 2023PUBLISHING YOUR PACKAGE TO APPEXCHANGEIN 2023
PUBLISHING YOUR PACKAGE TO APPEXCHANGEIN 2023
Bohdan Dovhań
 
Second-generation managed packages
Second-generation managed packagesSecond-generation managed packages
Second-generation managed packages
Bohdan 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 Update
Bohdan Dovhań
 
Salesforce Developer eXperience (SFDX)
Salesforce Developer eXperience (SFDX)Salesforce Developer eXperience (SFDX)
Salesforce Developer eXperience (SFDX)
Bohdan Dovhań
 
SFDX Presentation
SFDX PresentationSFDX Presentation
SFDX Presentation
Bohdan Dovhań
 
Sdfc forbidden and advanced techniques
Sdfc forbidden and advanced techniquesSdfc forbidden and advanced techniques
Sdfc forbidden and advanced techniques
Bohdan Dovhań
 
SFDC REST API
SFDC REST APISFDC REST API
SFDC REST API
Bohdan Dovhań
 
Being A Salesforce Jedi
Being A Salesforce JediBeing A Salesforce Jedi
Being A Salesforce Jedi
Bohdan Dovhań
 
Salesforce REST API
Salesforce  REST API Salesforce  REST API
Salesforce REST API
Bohdan Dovhań
 
Salesforce certifications process
Salesforce certifications processSalesforce certifications process
Salesforce certifications process
Bohdan Dovhań
 
Salesforce for marketing
Salesforce for marketingSalesforce for marketing
Salesforce for marketing
Bohdan 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 salesforce
Bohdan Dovhań
 
ExtJS Sencha Touch
ExtJS Sencha TouchExtJS Sencha Touch
ExtJS Sencha Touch
Bohdan Dovhań
 
PUBLISHING YOUR PACKAGE TO APPEXCHANGEIN 2023
PUBLISHING YOUR PACKAGE TO APPEXCHANGEIN 2023PUBLISHING YOUR PACKAGE TO APPEXCHANGEIN 2023
PUBLISHING YOUR PACKAGE TO APPEXCHANGEIN 2023
Bohdan Dovhań
 
Second-generation managed packages
Second-generation managed packagesSecond-generation managed packages
Second-generation managed packages
Bohdan 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 Update
Bohdan 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 techniques
Bohdan Dovhań
 
Being A Salesforce Jedi
Being A Salesforce JediBeing A Salesforce Jedi
Being A Salesforce Jedi
Bohdan Dovhań
 
Salesforce certifications process
Salesforce certifications processSalesforce certifications process
Salesforce certifications process
Bohdan Dovhań
 
Salesforce for marketing
Salesforce for marketingSalesforce for marketing
Salesforce for marketing
Bohdan 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 salesforce
Bohdan Dovhań
 
Ad

Recently uploaded (20)

IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...
Rishab Acharya
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfHow to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
QuickBooks Training
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!
PhilMeredith3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
SheenBrisals
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...
Rishab Acharya
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfHow to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
QuickBooks Training
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!
PhilMeredith3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
Eliminate the complexities of Event-Driven Architecture with Domain-Driven De...
SheenBrisals
 

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 sourceRecords, SObjectType dest, Map 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{ 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.
  • 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.