Skip to main content
Hi All, 

I have a simple requirement wherein a WorkOder record should be created when a Case is created. Now the challenge here is , there are around 20 fields that needs to be mapped to the workorder from the case. One way is mapping each fields in the trigger on insertion. But, later point in time the there would be some addition to this list. So, I was planning to use Custom Metadata to store the field mappings and try and use it in the code while inserting Workorder records. 

My Custom Metadata will look like:

Trigger to create a workOrder on Case creation using field mapping from Custom metadata

The trigger code is:

public static void createEmergencyWO(List<Case> newItems, Map<Id, Case> newItemsMap, Map<Id, Case> oldItemsMap){

        

        try {

        //Declare the list of related WO

        List<WorkOrder> woList = new List<WorkOrder>();

            //Query the metadata. This is a sample reference

            AccountFieldMapping__mdt[] threatMappings = [SELECT Contact_Fields__c,DeveloperName,Entity_relation__c,Field_Relation__c,Id,MasterLabel FROM AccountFieldMapping__mdt]; 

            for(Case caseRec : newItems){

                //How do I make use of metadata field mappings to create WorkOrder

                woList.add(add the metadata);

            }

        } 

        catch(Exception ex){

            

        }

        

    }

 
1 risposta
  1. 7 apr 2018, 20:00
    Hi Satish ,

    You will need to do the following to use the metadata/ custom setting for mapping in the apex code.

    Map<String , String> mapOfFieldMapping = new Map<String , String>();

    for(Mapping__c mapObj : [Select CaseMapping__c, WorkOrderMapping__c from Mapping__c]){

    mapOfFieldMapping.put(mapObj.WorkOrderMapping__c , mapObj.CaseMapping__c);

    }

    for(Case caseRec : newItems){

    WorkOrder workOrderObj = new WorkOrder();

    for(String workOrderField : mapOfFieldMapping.keyset()){ //iterate the Workorder field Name

    workOrderObj.put(workOrderField , caseRec.get(mapOfFieldMapping.get(workOrderField))); // get fieldname of case ,then it's record value using get method

    }

    woLIst.add(workOrderObj);

    }

    if(woLIst.size() > 0){

    insert woLIst;

    }

    Hope this helps.

     
0/9000