You need to sign in to do that
Don't have an account?

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;
}
}
}
}
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;
}
}
}
}
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.
Please do let me know if it helps you.
Regards,
Mahesh