function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
IT Admin 35IT Admin 35 

Update pricebook entry when product is updated

I would like to write a trigger on product that will insert/update the pricebook when a product is inserted or updated.
The following code does not seem to work. Sorry new to Apex coding

trigger TrgPricebookEntry on Product2 (after insert, after update)
{
    Set<ID> ids = Trigger.newMap.keySet();
    sObject s = [select ID from Pricebook2 where IsStandard = TRUE and IsActive= TRUE];

    list<PricebookEntry> entries=new list<PricebookEntry>();

    if(trigger.isinsert)
    {
        for (Product2 p : Trigger.new)
        {
            entries.add( new PricebookEntry( Pricebook2Id=s.ID, Product2Id=p.ID, UnitPrice=p.Price__c, IsActive=p.IsActive, UseStandardPrice=FALSE) );
        }
        insert entries;
    }

    list<PricebookEntry> pbe = [SELECT Id FROM PricebookEntry WHERE Product2ID in : ids];
            
    if(trigger.isupdate)
    {
        for (Product2 p : Trigger.new)
        {
            if (pbe != null)
            {
                pbe.UnitPrice=p.Price__c;
            }
        }
    }
}

 
Mahesh DMahesh D
Hi IT,

Please find the modified code:

Here I followed:

(1) Naming Convention
(2) Null checks.
(3) Bilkified the code.
(4) Tested the solution in my DE environment and it looks good.

 
trigger TrgPricebookEntry on Product2 (after insert, after update) {
    
    Set<ID> prodIdSet = Trigger.newMap.keySet();
    
    Pricebook2 pb = [select ID from Pricebook2 where IsStandard = TRUE and IsActive = TRUE];

    List<PricebookEntry> pbeList = new List<PricebookEntry>();

    if(trigger.isinsert) {
        for (Product2 p : Trigger.new) {
            pbeList.add( new PricebookEntry( Pricebook2Id = pb.ID, Product2Id=p.ID, UnitPrice = p.Price__c, IsActive = p.IsActive, UseStandardPrice = FALSE));
        }
        
        insert pbeList;
    }    
            
    if(trigger.isupdate) {
        List<PricebookEntry> existPBEList = [SELECT Id, UnitPrice, Product2Id FROM PricebookEntry WHERE Product2ID in : prodIdSet];
        if(existPBEList != null && !existPBEList.isEmpty()) {
            Map<Id, PriceBookEntry> prodPBEMap = new Map<Id, PriceBookEntry>();
            for(PricebookEntry pbe: existPBEList) {
                prodPBEMap.put(pbe.Product2Id, pbe);
            }
            
            for (Product2 p : Trigger.new) {
                PriceBookEntry tempPBE = prodPBEMap.get(p.Id);
                if (tempPBE != null) {
                    tempPBE.UnitPrice=p.Price__c;
                }
            }
            update prodPBEMap.values();
        }
    }
}

Please do let me know if it helps you.

Regards,
Mahesh
Gopal ChatGopal Chat
but its not working in my org