Wednesday, 16 January 2019

Populating standard price value in other object field

trigger PopulateStandardPrice2 on Product2 (before insert,before update,after insert,after update) {
    list<Id> Idlist = new list<Id>();
    list<product2> ProdsToUpdate = new list<Product2>();
    for(Product2 pr:Trigger.new){
        Idlist.add(pr.Id);
    }
    pricebook2 pb = [select Id from pricebook2 where IsStandard = TRUE LIMIT 1];


        Map<string,product2> productMap = new Map<String,Product2>();
        for(product2 p:[select StandardPrice__c,Id from product2 where Id IN :Idlist]){
             productMap.put(p.Id,p);
        }

        for(pricebookentry pbe:[select Product2Id,UnitPrice from pricebookentry where pricebook2Id = :pb.Id and product2Id IN :Idlist]){
            If((pbe.Product2Id == productMap.get(pbe.Product2Id).Id)&&(productMap.get(pbe.Product2Id).StandardPrice__c!=pbe.UnitPrice)){
                productMap.get(pbe.Product2Id).StandardPrice__c = pbe.UnitPrice;
                ProdsToUpdate.add(productMap.get(pbe.Product2Id));
            }
        }
    If(ProdsToUpdate.size()>0&&Trigger.isafter){
            update ProdsToUpdate;
    }
}