Tuesday, 11 October 2016

Building Dynamic Triggers and Fieldset !!

Hi Folks,

Isn't it awesome if you are able to create trigger and fieldset dynamically :)

1) Create Trigger Dynamically :
map<string,string> mapinfo= new map<string,string>();
mapinfo.put('Name','AccountTrigger');
mapinfo.put('TableEnumOrId','Account');
mapinfo.put('Body','trigger AccountTrigger on Account(after insert){}');
String serialized = JSON.serialize(mapinfo);
         
Httprequest req = new HttpRequest();
req.setEndpoint('https://ajaytrailhead-dev-ed.my.salesforce.com/services/data/v27.0/sobjects/ApexTrigger'); // Enter the org.
req.setMethod('POST');
req.setHeader('Content-Type','application/json');
req.setHeader('Authorization','Bearer '+UserInfo.getSessionID());
req.setBody(serialized);

Http httpReq = new Http();
HttpResponse res = httpReq.send(req);
System.debug(res.getBody());

2) Create FieldSet Dynamically :

To make it possible you need to add the following class to your org.

https://github.com/financialforcedev/apex-mdapi/blob/master/apex-mdapi/src/classes/MetadataService.cls

Use below code to create fieldset dynamically :

public with sharing class DynamicFieldSetCreator
{
public static MetadataService.MetadataPort createService()
{
 MetadataService.MetadataPort service = new MetadataService.MetadataPort();
 service.SessionHeader = new MetadataService.SessionHeader_element();
 service.SessionHeader.sessionId = UserInfo.getSessionId();
 return service;
}
   
public static void createFieldSet()
{
        MetadataService.MetadataPort service = createService();

MetadataService.FieldSet fieldSet = new MetadataService.FieldSet();
        fieldSet.fullName = 'Account.MyFieldSet'; // You can use custom object also.                                                                                                             //Mycustomobject__c.MyFieldSet
        fieldSet.label = 'My FieldSet';
        fieldSet.description = 'Demo fieldset';

        MetadataService.FieldSetItem myAvailableField = new MetadataService.FieldSetItem();
        myAvailableField.field = 'Name'; // Add standard/custom fields to be included in fieldset
        myAvailableField.isFieldManaged = true;
        myAvailableField.isRequired = true;

        fieldSet.availableFields = new List<MetadataService.FieldSetItem>();
        fieldSet.availableFields.add(myAvailableField);

        List<MetadataService.SaveResult> results =
            service.createMetadata(new MetadataService.Metadata[] { fieldSet });
        handleSaveResults(results[0]);
}

public static void handleSaveResults(MetadataService.SaveResult saveResult)
    {
        if(saveResult==null || saveResult.success)
            return;

        // Handle Errors
        if(saveResult.errors!=null)
        {
            List<String> Erros = new List<String>();
            Erros.add(
                (saveResult.errors.size()==1 ? 'Error ' : 'Errors ') +
                    'occured processing component ' + saveResult.fullName + '.');
            for(MetadataService.Error error : saveResult.errors)
                Erros.add(
                    error.message + ' (' + error.statusCode + ').' +
                    ( error.fields!=null && error.fields.size()>0 ?
                        ' Fields ' + String.join(error.fields, ',') + '.' : '' ) );
            if(Erros.size()>0)
            {
                system.debug('>>>>>>>>>>>>>Here');
               
             }
        }
        if(!saveResult.success)
        {
            system.debug('>>>>>>>>>>>>>HereAlso');
        }
    }
}

Keep Coding !!!!