I need to create all the fields available in a specific Standard object to a custom object using Apex code. Is this possible?

  • Also consider that in a live org you will have to modify profiles/permission sets and layouts too.
    – Keith C
    Oct 25 '16 at 10:39

You will have to use Metadata API for that. This API provides function to work with Salesforce Metadata including create, edit, delete of fields. You can check it out here: https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_intro.htm

There is a Github code which provides Apex methods to use the Metadata API. This is developed by Andrew Fawcett and you can find it here: https://github.com/financialforcedev/apex-mdapi

Happy Coding!


You could use Metadata API for this.

However, I would strongly advice against doing that. To create a field on production means to alter metadata, which required deployment. Deployment requires code coverage.

If you need to deploy some fields to Production, you should better use Changesets or ANT Migration Tool.


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

For example-

String objectapiname = 'Content_Item__c';//replace with your object name
String fieldapiname = 'GCP_Country_Name';//replace with your field name
String fieldlabel = 'GCP_Country_Name';//replace with your field label
String fielddescription = 'GCP Country Name';//replace with your field label
HttpRequest requestinside = createHttpRequest(, 'POST');
requestinside.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
requestinside.setHeader('Content-Type', 'application/json');
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"}';

HTTPResponse res = http.send(requestinside);

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.