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
FacebookFacebook 

Trigger for creating a pricebook entry

HI,

 

 When a Product is created or edited, create a Price Book Entry in the Standard Price Book with the Advertised Price from the input record.

 

For this i wrote the following Trigger

 

trigger TrgPricebookEntry on Product2 (before insert,before update) {
list<Product2> lstproduct=new list<Product2>();
list<PricebookEntry> lstPbe=new list<PricebookEntry>();
PricebookEntry PB;
 if(trigger.isinsert){
   for(Product2 objProduct:trigger.new)
      {
    PB=new PricebookEntry();
    PB.UnitPrice=objProduct.Advertised_Price__c;
    PB.UseStandardPrice=true;
    PB.IsActive=true;
    PB.Pricebook2Id=objProduct.id;
    lstPbe.add(PB);
    }
    insert lstPbe;
 }
 if(trigger.isUpdate){
   for(Product2 objProduct:trigger.new)
      {
    PB=new PricebookEntry();
    PB.UnitPrice=objProduct.Advertised_Price__c;
    PB.UseStandardPrice=true;
    PB.IsActive=true;
    PB.Pricebook2Id=objProduct.id;
    lstPbe.add(PB);
    }
    insert lstPbe;
 }
}

 

 

But it is not working.Any Help regarding this is highly appreciated.

 

 

Regards,

Abhi

MikeGillMikeGill

This one had me stumped for ages

 

Run this using Execute Anonymous to see it working

 

 

Product2 product = new Product2 (Name = 'MyItem' , IsActive = true);
insert product;
Pricebook2 stdPrice = [Select id from Pricebook2 where isStandard=true limit 1];
PricebookEntry priceBookEntry = new PricebookEntry( IsActive = true, Product2Id = product.id, UnitPrice = 1.00, Pricebook2Id = stdPrice.Id);
insert priceBookEntry;

 

This should help you.

 

FacebookFacebook

Hi,

 

       Thanks Gill.Its working in Execute anonymous.But my question is how can we use it in the trigger?

 

 

Regards,

Abhi

 

 

 

        

MikeGillMikeGill

I hope this helps you - remove the UseStandardPrice = true

 

 

Product2 product = new Product2 (Name = 'MyItem' , IsActive = true);
insert product;
Pricebook2 stdPrice = [Select id from Pricebook2 where isStandard=true limit 1];
PricebookEntry priceBookEntry = new PricebookEntry( IsActive = true, Product2Id = product.id, UnitPrice = 2.00, Pricebook2Id = stdPrice.Id);
insert priceBookEntry;
PricebookEntry updatePriceBookEntry = new PricebookEntry( id = priceBookEntry.Id, UnitPrice = 3.00);
update updatePriceBookEntry;