function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Christopher EvenChristopher Even 

How to dynamically add customfields to non custom objects (Lead, Account)

From my experimentation with the metadata api, it appears to only allow the creation of custom fields on custom objects. 
Is this really the case?
Any suggestions on how i can programatically add 1 to N fields to say the "Lead" object?
I will not know ahead of time on how many fields there are so a package update probably won't work.
Any sample code is appreciated. 
AbhishekAbhishek (Salesforce Developers) 
Hi,

If you really want to do this through code, you can engage the "Metadata API" to create objects and fields. You can do this via Java or Apex... though the approaches will be quite different. If you want to do it via Java you will have to overcome OAuth authentication etc. to access the APIs (standard oAuth library for that) if you develop a solution in Apex inside the Salesforce organization you can just tap up the APIs straight off (I believe!)

So here is a link to the Metadata API create() function: https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_create.htm

And there are examples here of how to use that to send the definition of a new object (using Apex):
https://github.com/financialforcedev/apex-mdapi/blob/master/apex-mdapi/src/classes/MetadataServiceExamples.cls#L35


You should be able to take that example and just fire an object into an Org if you want.. hopefully that will get you going? All you have to do then is copy and paste the code a bunch of times to insert the objects and fields you desire!


And you can also try the code as mentioned in the below blog,

https://developer.salesforce.com/forums/?id=906F000000092lfIAA

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks.
 
sachinarorasfsachinarorasf
Hi Christopher,

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

Here is the url of Metadata Api
https://github.com/financialforcedev/apex-mdapi

Thanks and Regards,
Sachin Arora
www.sachinsf.com