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
Atomic_ForceAtomic_Force 

Help with Trigger on Product2 - Urgent help please!!

Need to update a custom boolean field on Product2 if PricebookEntry UnitPrice > 0.  Here is the simple trigger that I started to update the value of Product2 In_Pricelist__c field.  How do I get this portion of the trigger to work and then iterate over PricebookEnties to see if Product2Id is in list and UnitPrice > 0?

trigger trueInPricelist on Product2 (before update) {
   
   List<Product2> prods2update = new list<Product2>();
   
        for(Product2 prods : trigger.new){
            if(prods.In_Pricelist__c == Null){
                prods2update.add(prods);
        }
        if(prods2update.size() > 0){
        	for (Product2 p : prods2update){
        		p.In_Pricelist__c = True;
        		    
        }
        }
        update prods2update;
        }
}

 

Best Answer chosen by Admin (Salesforce Developers) 
JHayes SDJHayes SD

This worked for me:  

 

trigger trueInPricelist on Product2 (before update) {
   
    // Fetches all associated pricebook entries with UnitPrice > 0.
    List<PricebookEntry> pbes = 
        [SELECT Product2.Id FROM PricebookEntry WHERE Product2.Id IN :trigger.newMap.keySet() AND UnitPrice > 0];
    
    // productIds will contain the set of product ids tied to pricebook entries with UnitPrice > 0
    Set<Id> productIds = new Set<Id>();
    for (PricebookEntry pbe : pbes) {
        productIds.add(pbe.Product2Id);
    }   

    // Update the field as needed    
    for (Product2 p : trigger.new) {
        if (productIds.contains(p.Id)) {
            p.In_Pricelist__c = true;
        }
    }
}

 

 

Give it a shot and let me know if it works for you.

 

Regards, jh

All Answers

JHayes SDJHayes SD

This worked for me:  

 

trigger trueInPricelist on Product2 (before update) {
   
    // Fetches all associated pricebook entries with UnitPrice > 0.
    List<PricebookEntry> pbes = 
        [SELECT Product2.Id FROM PricebookEntry WHERE Product2.Id IN :trigger.newMap.keySet() AND UnitPrice > 0];
    
    // productIds will contain the set of product ids tied to pricebook entries with UnitPrice > 0
    Set<Id> productIds = new Set<Id>();
    for (PricebookEntry pbe : pbes) {
        productIds.add(pbe.Product2Id);
    }   

    // Update the field as needed    
    for (Product2 p : trigger.new) {
        if (productIds.contains(p.Id)) {
            p.In_Pricelist__c = true;
        }
    }
}

 

 

Give it a shot and let me know if it works for you.

 

Regards, jh

This was selected as the best answer
Atomic_ForceAtomic_Force

Awesome!  Thank you so much.  Really appreciate the help.  Works almost perfect.  Adding some conditional statements to the trigger.new loop.