How to connect to Salesforce metadata API from a Visualforce Page

Meatadat API allows you to connect to Salesforce to create, modify and delete Salesforce metadata. This API is designed for external systems/clients to connect to Salesforce. But there will be use cases where you need to connect to metadata API from Salesforce itself and make changes to the metadata in same org/sandbox.

In this blog we will go through creating a custom visualforce page that you can use to connect to Salesforce metadata API and create objects in Salesforce.

Use cases

  • Update metadata(create objects, create fields, page layouts etc) from visualforce
  • To provide a single user interface for admins to do different actions that otherwise would require going through different setup sections (Example :- post installation setup of complex appexchange apps)


Explanation

We are using jsforce library to interact with Salesforce metadata. In this particular example we are creating a custom object in Salesforce. First we load jsforce library from CDN using apex:includeScript tag. Then we initialize salesforce connection in jsforce library with logged in user's session id. createObject function reads label and API name of desired object from HTML input tags and calls jsforce method available on connection instance conn.metadata.create. We are passing metadata type, object metadata as a JSON array and a callback function to this method. Once Salesforce has processed the request, callback will be called with error/success response. To simplify things we are just alerting the result we are getting in the callback. But we can definitely build a good user interface and provide complex metadata manipulation functionalities using the ability to interact with metadata.

Creating an object is just an example usecase. You can do a lot more things with jsforce library. Examples can be found in jsforce documenation. jsforce metadata


How to use

  • Create a visualforce page in your org
  • Copy paste above code into your page. There is no controller or other dependencies.
  • Go to below url to see the resulting page
    {{yourSalesforceBaseUrl}}/apex/{{NameOfThePageYouCreated}}

2 comments:

  1. Anyone looking for Salesforce app which save their time and can perform bulk CRUD operations in few click - their search end at Salesforce Appexchange app Bulk Object Field Creator
    Most recommended and appreciable app by Salesforce MVP

    ReplyDelete