[SalesForce] Check if User has Permission to update Custom Metadata

I'm building Visualfroce for updating Custom Metadata.

When User without required permissions tries to update them he gets
error message

I tried checking MetadataType__mdt.getSObjectType().getDescribe().isUpdatable(), but it returns false even for System Admin.

I know that I can query Profile and all associated Permission Sets to check if User has CustomizeApplication System Permission, but maybe there is a better way.

Please share your insights if you know of any other way to check it in Apex.

UPDATE:

I've already implemented functionality for updating Custom Metadata using Metadata API.

This error is thrown by Visualforce if the page has and User doesn't have permission necessary to update Custom Metadata.

Best Answer

Custom Metadata Type records cannot be updated via direct DML like

update myCMTRecord;

by anyone, including system administrators, because that's not supported in Apex at all.

To modify Custom Metadata in Apex, you must use the Apex Metadata API to perform an asynchronous deploy operation.

The Apex Metadata API essentially passes security through to the underlying Metadata API:

Apex Metadata API deployments always respect Metadata API permissions. Although you can write Apex code that lets end users enqueue a deployment, that deployment fails if the users don’t have the correct Metadata API permissions.

which requires the Modify All Data and API Enabled permissions, or the beta Modify Metadata permission.

I'd suggest taking two tacks here:

  • Since there will soon be multiple ways to obtain access to the Metadata API, it's probably a more stable approach to expose the editing interface based on a higher-level grouping, like System Administrators only, or an org-specific permission set that you establish. Check for that qualification before allowing the user to begin editing, so that you can show a friendly error message.
  • Use a wrapper class to hold values that are intended to be persisted as a CMT record during the editing process and bind Visualforce components only to the wrapper class. This would allow you to centralize permission management in the method which initiates the metadata update or insert operation, where you'd convert those wrappers into actual CMT records to pass to Apex.
Related Topic