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
SunnyalexSunnyalex 

Apex Methods

public class MetadataUtility{

    public static void generateTextField(String objectAPIName, String fieldAPIName, String fieldDescription, String fieldLabel){
        String metadata = '{"Metadata" : {"type" : "Text","description" : "'+fieldDescription+'", "inlineHelpText" : "","precision" : null,"label" : "'+fieldLabel+'","length" : 255,"required" : false}, "FullName" : "'+objectAPIName+'.'+fieldAPIName+'"}';

        String responseBody = createField(metadata);
    }

    public static void generateFormulaField(String objectAPIName, String fieldAPIName, String fieldDescription, String fieldLabel, String retrunType, String validFormula){
        
        String metadata = '{"Metadata" : {"type" : "'+retrunType+'","description" : "'+fieldDescription+'", "formula" : "'+String.escapeSingleQuotes(validFormula)+'","formulaTreatBlanksAs" : "BlankAsZero","label" : "'+fieldLabel+'"}, "FullName" : "'+objectAPIName+'.'+fieldAPIName+'"}';
        String responseBody = createField(metadata);
        system.debug(responseBody);
    }
    
    
    public static String createField(String metadata) {
        HttpRequest request = new HttpRequest();
        request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
        request.setHeader('Content-Type', 'application/json');
        request.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v46.0/tooling/sobjects/CustomField');
        request.setMethod('POST');
        
        request.setBody(metadata);
        
        Http http = new Http();
        HTTPResponse res = http.send(request);
        return res.getBody();
    }
}
...............................................................................................................
with this methods i am only able to create Text field and Formula field how to write methods  for phone,Date,Email,Number,Picklist etc
ShirishaShirisha (Salesforce Developers) 
Hi Sunny,

Greetings!

You can find the sample code in the below blog to create the custom field by using the type according to your requirement.

https://github.com/financialforcedev/apex-mdapi

Please mark it as best answer if it helps you to fix the issue.

Thank you!

Regards,
Shirisha Pathuri
SunnyalexSunnyalex
Hello Shirisha I am not getting here in this link also I just want to create fields for standard object and here in this link again same custom object is showing can you please tell me how do I create fields in standard object