Apex Code to Create Custom Field Programmatically

Ayub Ansari
2 min readDec 4, 2020

--

DESCRIPTION

It’s very typical to get such a scenario when we need to create custom field programmatically. Previously, we used to use Metadata API for the same which was very costly.

But now, Tooling API provides an efficient way to achieve it. I’ve prototyped in below class. You can create custom fields as given below.

APPROACH

Below given code is metadata driven, so for each type of field,

  • You need to get the metadata. Below is a tip to get metadata.
  • You can get required metadata using workbench –> Rest Explorer and hit /services/data/v48.0/tooling/sobjects/CustomField/00N9000000DHfrM where ‘00N9000000DHfrM‘ is existing field with same data type. this call will return JSON response where you can extract metadata and manipulate as per your requirement.
  • You will need to create remote site setting for the given endpoint which is base URL of your salesforce org.

Copy the following utility apex class:

public class MetadataUtility{

public static void generateTextField(String objectAPIName, String fieldAPIName, String fieldDescription, String fieldLabel){
String metadata = '{"Metadata" : {"type" : "Text","description" : "'+fieldDescription+'", "inlineHelpText" : "","precision" : null,"label" : "'+fieldLabel+'","length" : 255,"required" : false}, "FullName" : "'+objectAPIName+'.'+fieldAPIName+'"}';

String responseBody = createField(metadata);
}

public static void generateFormulaField(String objectAPIName, String fieldAPIName, String fieldDescription, String fieldLabel, String retrunType, String validFormula){

String metadata = '{"Metadata" : {"type" : "'+retrunType+'","description" : "'+fieldDescription+'", "formula" : "'+String.escapeSingleQuotes(validFormula)+'","formulaTreatBlanksAs" : "BlankAsZero","label" : "'+fieldLabel+'"}, "FullName" : "'+objectAPIName+'.'+fieldAPIName+'"}';
String responseBody = createField(metadata);
system.debug(responseBody);
}

public static String createField(String metadata) {
HttpRequest request = new HttpRequest();
request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
request.setHeader('Content-Type', 'application/json');
request.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v46.0/tooling/sobjects/CustomField');
request.setMethod('POST');

request.setBody(metadata);

Http http = new Http();
HTTPResponse res = http.send(request);
return res.getBody();
}
}

Examples of Usage:

MetadataUtility.generateTextField(‘Account’, ‘Type_x__c’, ‘Text Field created by apex’, ‘Type (apex)’);

//Parameter “validFormula” is important and it should be correct and formatted to support JSON.

MetadataUtility.generateFormulaField('Account', 'Ac_Name__c', 'formula Field created by apex', 'Account Name (Formula)', 'Text', '(Name)');

--

--