Create Salesforce Custom Object Using Apex Code

|
| By Webner

Salesforce custom object using apex code

There are two ways of creating a custom object and its related fields in Salesforce. The first and the easiest way is to go to the Objects link beneath Create tab, click on the new button and create a new object as required. Another approach is to create it using code dynamically. For the latter approach, we have to download a Metadata service which can be found on the internet. Make sure it contains the function “createMetadata” which we will use in our code. This class comes in a package, but you can download the specific MetadataService.class file to execute the below code.

(Note: Check the link at the end of the page)

* Create custom object:

MetadataService.MetadataPort metadataservice = new MetadataService.MetadataPort();
metadataservice .SessionHeader = new MetadataService.SessionHeader_element();
metadataservice .SessionHeader.sessionId = UserInfo.getSessionId();

List fields = new List();
MetadataService.CustomObject customobject = new MetadataService.CustomObject();
customobject.fullName = ‘custom_create__c’;
customobject.label = ‘Custom created object’;
customobject.pluralLabel = ‘Custom created objects’;

fields.add(customobject);
metadataservice.createMetadata(fields);

* Create custom field:

MetadataService.MetadataPort metadataservice = new MetadataService.MetadataPort();
metadataservice .SessionHeader = new MetadataService.SessionHeader_element();
metadataservice .SessionHeader.sessionId = UserInfo.getSessionId();

List fields = new List();
MetadataService.CustomField customField = new MetadataService.CustomField();
customField.fullName = ‘custom_create__c.custom_create_field__c’;
customField.label = ‘Custom created field’;
customField.defaultvalue = ‘false’;
customField.type_x = ‘Checkbox’;
fields.add(customField);
metadataservice.createMetadata(fields);

Helper class for the above code:

https://github.com/financialforcedev/apex-mdapi/blob/master/apex-mdapi/src/classes/MetadataService.cls

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *