Activity Forums Salesforce® Discussions Can we create a custom field through Salesforce Apex?

  • Adarsh

    Member
    March 22, 2018 at 1:08 pm

    Hi Ankit,

    Yes, it is possible through Metadata API's but not directly via apex.

    You can't access the metadata API via Apex.  It's a web service API used by external clients.

    Hope it helps 🙂

  • Neha

    Member
    March 23, 2018 at 5:07 am

    Hi Ankit,

    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 need to first generate the apex class through Metadata WSDL , then with the help following code you can create field through Apex.

    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 });

    Hope this help you..

  • Archit

    Member
    March 23, 2018 at 11:32 am

    Hello Ankit,

    Please try the below code it may help you to achieve your task

    MetadataService.CustomObject customObject = new MetadataService.CustomObject();
    customObject.fullName = 'Test__c';
    customObject.label = 'Test';
    customObject.pluralLabel = 'Tests';
    customObject.nameField = new MetadataService.CustomField();
    customObject.nameField.type_x = 'Text';
    customObject.nameField.label = 'Test Record';
    customObject.deploymentStatus = 'Deployed';
    customObject.sharingModel = 'ReadWrite';
    MetadataService.AsyncResult[] results = service.create(new List<MetadataService.Metadata> { customObject });

  • Pooja

    Member
    March 6, 2020 at 2:05 pm

    Yes, we can we create a custom field through Salesforce Apex.

  • Aditya

    Member
    March 6, 2020 at 4:39 pm

    Hi Ankit,

    Once you have imported the code, you can go back to your Salesforce account, and search for “apex classes.” Click the “new” button, then paste the metadata from this website. Once the metadata has been entered, you can run the apex code, and will be able to start creating custom objects and fields.

  • Anjali

    Member
    March 6, 2020 at 5:58 pm

    Yes, we can create custom field using Apex.

Log In to reply.

Popular Salesforce Blogs