trigger CicProMidTblBefUpd on CIC_and_product_middle_table__c (before insert, before update) { 
 | 
    List<Product2> pnList = new List<Product2>(); 
 | 
    for (CIC_and_product_middle_table__c cpmt : Trigger.new) { 
 | 
        if (Trigger.isInsert || Trigger.isUpdate && cpmt.Product__c != Trigger.oldMap.get(cpmt.Id).get('Product__c')) { 
 | 
            if (!String.isBlank(cpmt.Product__c)) { 
 | 
                pnList.add(new Product2(Id = cpmt.Product__c)); 
 | 
            } 
 | 
        } 
 | 
    } 
 | 
     
 | 
    Map<String, String> pr2Map = new Map<String, String>(); 
 | 
    if (pnList.size() > 0) { 
 | 
        List<Product2__c> pr2List = ControllerUtil.pr2SelectForSync(pnList); 
 | 
        for (Product2__c pr2 : pr2List) { 
 | 
            pr2Map.put(pr2.Product2__c, pr2.Id); 
 | 
        } 
 | 
    } 
 | 
     
 | 
    for (CIC_and_product_middle_table__c cpmt : Trigger.new) { 
 | 
        if (cpmt.Product__c != null && pr2Map.containsKey(cpmt.Product__c)) { 
 | 
            cpmt.Product2__c = pr2Map.get(cpmt.Product__c); 
 | 
        } else { 
 | 
            cpmt.Product2__c = null; 
 | 
        } 
 | 
    } 
 | 
} 
 |