I m trying to write an Apex trigger and class, to update a list-price of a Product in a Pricebook, once a checkbox is clicked on the product object. Here is all of my code:
Class:
public class UpdatePriceBook {
public static void UpdatePrice(Id productId, Id pricebookEntryId, Decimal newPrice){
try {
// Retrieve the product and pricebook entry
Product2 product = [SELECT Id, Name FROM Product2 WHERE Id = :productId];
PricebookEntry pricebookEntry = [SELECT Id, Product2Id, Pricebook2Id, UnitPrice FROM
PricebookEntry WHERE Id = :pricebookEntryId];
// Update the price
pricebookEntry.UnitPrice = newPrice;
// Save the updated pricebook entry
update pricebookEntry;
System.debug( Price updated successfully for product: + product.Name);
} catch (Exception e) {
System.debug( Error updating price: + e.getMessage());
}
}
}
Trigger:
trigger UpdateProductPrice on Product2 (before insert) {
if (Trigger.isBefore) {
if (Trigger.isInsert || Trigger.isUpdate) {
for (Product2 product : Trigger.new) {
if (product.ProductPriceUpdate__c) {
// Get the relevant PricebookEntry for this product
List<PricebookEntry> standardPricebookEntries = [
SELECT Id, UnitPrice
FROM PricebookEntry
WHERE Product2Id = :product.Id
AND Pricebook2.Name IN ( USA Pricebook , International PB )
AND Product2.Name = Cabinet
AND Pricebook2.IsStandard = true
LIMIT 1
];
// if (!pricebookEntries.isEmpty()) {
// Id pricebookEntryId = pricebookEntries[0].Id;
// Decimal newPrice = 1500; // Replace with your desired price
if (!standardPricebookEntries.isEmpty()) {
PricebookEntry standardPricebookEntry = standardPricebookEntries[0].id;
Id pricebookEntryId = pricebookEntries[0].Id;
Decimal newPrice = 1500; // Replace with your desired price
standardPricebookEntry.UnitPrice = newPrice;
UpdatePriceBook.UpdatePrice(product.Id, pricebookEntryId, newPrice); // Replace with your desired price
}
}
}
}
}
}
我所困的是——我需要获得标准。 缩略语 价格指数
I didn t realize when I started writing the code - that I was trying to modify the PricebookEntry object, but that isn t correct because the list price is a standardPricebookEntry field, not a PricebookEntry field, so that s how I have this line of code:
Id pricebookEntryId = pricebookEntries[0].Id;
但是,如果我想要改变,它就属于标准类型。 价格 加入:
PricebookEntry standardPricebookEntry = standardPricebookEntries[0].Id;
我发现这一错误:“从Id到PbookEntry进行非法转让”。
Thats because its assigning an id value to a PricebookEntry variable. But I do need the Id value - to pass to the class method - it s expecting to get an Id type parameter. What can I add to the code, or how can I modify it, to do what I described in the beginning of the question?