How can I add a product to a certain custom PriceBook depending on a product field? - Answers - Salesforce Trailblazer Community
Trailblazer Community
Ask Search:
Javier FloresJavier Flores 

How can I add a product to a certain custom PriceBook depending on a product field?

Hi everyone, 

I need to automatically add each product to a certain PriceBook depending on a picklist field of the product. For example, if the product company field has selected the "MW Piura" option value it should add its standard price to the PriceBook A, but if the product company field has selected "MW Lima" it should instead add the standard price to the PriceBook B. 

I have tried doing this by a process builder but I cannot get the PriceBook, only the PriceBook Entry but no capable to choose which PriceBook to add the PriceBook Entry. Or the only way is creating an apex Trigger on Product?

I would really appreciate your help!
Thanks in advance!
Best Answer chosen by Javier Flores
Javier FloresJavier Flores
I decided to go by the Apex Trigger Aproach, here is the final result working 100%
 
trigger filterCompany on Product2 (before insert, before update) {
    for(Product2 prods: Trigger.new){
        
        PricebookEntry pe = new PricebookEntry();
        //Checar si existe un pricebook entry correspondiente a su empresa
        PricebookEntry existencia = [SELECT CurrencyIsoCode, UnitPrice, IsActive, UseStandardPrice
                                     FROM PricebookEntry 
                                     WHERE Pricebook2Id =: prods.Empresa__c AND Product2Id =: prods.Id];
        if(existencia == null){
            Pricebook2 pb = [SELECT id FROM Pricebook2 WHERE Name =: prods.Empresa__c];
            pe.CurrencyIsoCode = 'USD';
            pe.Product2Id = prods.Id;
            pe.Pricebook2Id = pb.id;
            pe.UnitPrice = prods.Prec_Vta__c;
            pe.IsActive = prods.IsActive;
            pe.UseStandardPrice = false;
            Database.insert(pe);
        }else{
            existencia.CurrencyIsoCode = 'USD';
            existencia.Product2Id = prods.Id;
            existencia.UnitPrice = prods.Prec_Vta__c;
            existencia.IsActive = prods.IsActive;
            existencia.UseStandardPrice = false;
            Database.update(existencia);
        }

    }
}