5

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

11

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.

| improve this answer | |
4

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'
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/

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.