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
Ashritha SAshritha S 

automation of creating a custom field in salesforce

Hi ,

I have a json file which has the custom field details like field name, field type , field values etc.. How do I write a code to create a custom field in salesforce from this external json file.
Vijay NagarathinamVijay Nagarathinam
Hi,

Yes, You can create custom object fields using Apex code.

see the below example,

create a field using apex
MetadataService.MetadataPort service = new MetadataService.MetadataPort();  
service.SessionHeader = new MetadataService.SessionHeader_element();
service.SessionHeader.sessionId = UserInfo.getSessionId();

List<MetadataService.Metadata> fields = new List<MetadataService.Metadata>();
MetadataService.CustomField customField = new MetadataService.CustomField();
customField.fullName = 'custom_create__c.custom_create_field__c';
customField.label = 'Custom created field';
customField.defaultvalue = 'false';
//customField.sharingModel = 'ReadWrite';
customField.type_x = 'Checkbox';
fields.add(customField);

MetadataService.AsyncResult[] results = service.create(fields);


 
Ashritha SAshritha S
I inserted MetadataService and MetadataServiceTest controller in my developer account. I ran the code which you gave as a method in another class MetadataServiceExample but still I am getting "Method does not exist or incorrect signature: [MetadataService.MetadataPort].create(LIST<MetadataService.Metadata>) at line 19 column 41" as error. 
Vijay NagarathinamVijay Nagarathinam
Hi Ashritha,

Try this code,
 
public static void createField()
    {
        MetadataService.MetadataPort service = createService();     
        MetadataService.CustomField customField = new MetadataService.CustomField();
        customField.fullName = 'Test__c.TestField__c';
        customField.label = 'Test Field';
        customField.type_x = 'Text';
        customField.length = 42;
        List<MetadataService.SaveResult> results =    service.createMetadata(
                new MetadataService.Metadata[] { customField });                
        handleSaveResults(results[0]);
    }

 
Ashritha SAshritha S
Hi , I learnt to create custom fields using services of metadata api. Thank you , this information was helpful.

But I am facing an issue while creating custom fields for case as  ' limit exceeded ' while using the metadata service. Initially I could create few fields for case object both using the GUI of salesforce and also using metadata service . Now I am not able to creating custom fields for case from both the options. Even when I am using the GUI of salesforce to create a custom field for case its throwing an error as ' No clean data columns available for custom fields.'