Activity Forums Salesforce® Discussions How to add Custom Field on Particular Object through Salesforce Apex Class?

  • Shaharyar

    Member
    August 4, 2017 at 9:49 am

     

    Please try this it will work.

    public static void createObject()
    {
    MetadataService.MetadataPort service = createService();
    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';
    List<MetadataService.SaveResult> results =
    service.createMetadata(
    new MetadataService.Metadata[] { customObject });
    handleSaveResults(results[0]);
    }

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

     

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos