9

Anybody knows how to create custom text fields on salesforce.com objects using apex?

2 Answers 2

14

You can do that by using the metadata API and a web service written by Andrew Fawcett that you can find here.

Example:

MetadataService.CustomField customField = new MetadataService.CustomField();
customField.fullName = 'Test__c.TestField__c';
customField.label = 'Test Field';
customField.type_x = 'Text';
customField.length = 42;
MetadataService.AsyncResult[] results =   service.create(new List<MetadataService.Metadata> { customField });

And here is the original thread.

1
  • On the last line, you refer to a variable called service but this has not been defined.
    – NickJ
    Commented Apr 11, 2022 at 16:32
11

As a technical evolution, Salesforce has made very easy to create the field by using tooling api...

For example-

String objectapiname = 'Content_Item__c';//replace with your object name
String fieldapiname = 'Country_Name';//replace with your field name
String fieldlabel = 'Country_Name';//replace with your field label
String fielddescription = 'Country Name';//replace with your field label

HttpRequest requestinside = new HttpRequest();
requestinside.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
requestinside.setHeader('Content-Type', 'application/json');
requestinside.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v41.0/tooling/sobjects/CustomField/');
requestinside.setMethod('POST');
String fieldDef = '{"Metadata" : ';
String metadef = '"type" : "Text","description" : "'+fielddescription+'", "inlineHelpText" : "","precision" : null,"label" : "'+fieldlabel+'","length" : 255,"required" : false'; //added missing semi-colon
fieldDef += '{'+metadef+'},';
fieldDef += '"FullName" : "'+objectapiname+'.'+fieldapiname+'__c"}';
system.debug(fieldDef);
requestinside.setBody(fieldDef);
HTTPResponse res = http.send(requestinside);
System.debug(res.getBody());

https://sfdcian.com/apex-code-to-create-custom-field-programmatically/

3
  • 1
    Thanks man! Converted to python version in case if anyone needs it: stackoverflow.com/questions/65332251/… Commented Dec 16, 2020 at 22:56
  • Glad it helped. Thanks for posting python version.
    – Ayub
    Commented Dec 17, 2020 at 5:16
  • 1
    this is the best answer by a mile. One small change would be to create a Metadata class and JSON.serialize() it instead of building the JSON by hand. Other than that, great answer.
    – NickJ
    Commented Apr 11, 2022 at 17:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .