Activity › Forums › Salesforce® Discussions › Can we create a custom field through Salesforce Apex?
-
Can we create a custom field through Salesforce Apex?
Posted by Ankit on March 22, 2018 at 1:05 PMCan we create a custom field through Salesforce Apex?
Anjali replied 6 years, 2 months ago 7 Members · 6 Replies -
6 Replies
-
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 🙂
- [adinserter block='9']
-
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..
-
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 }); -
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.
Log In to reply.