9

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

Boris Bachovski
  • 16,216
  • 8
  • 47
  • 85
Saulo
  • 957
  • 1
  • 8
  • 23

2 Answers2

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.

Boris Bachovski
  • 16,216
  • 8
  • 47
  • 85
  • On the last line, you refer to a variable called service but this has not been defined. – NickJ Apr 11 '22 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/

Ayub
  • 3,503
  • 19
  • 31
  • 1
    Thanks man! Converted to python version in case if anyone needs it: https://stackoverflow.com/questions/65332251/how-to-create-custom-field-via-api – TitanFighter Dec 16 '20 at 22:56
  • Glad it helped. Thanks for posting python version. – Ayub Dec 17 '20 at 05: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 Apr 11 '22 at 17:06