I'm making a Trigger that when adding a product to the Opportunities object when updating the Quantity if placed below the original value an error will appear, but when increasing the date field it would have to be updated automatically to the current day
but it's giving an error, what could I be doing or what am I doing wrong?
OpportunityLineItemTrigger: execution of BeforeUpdate caused by: System.FinalException: Record is read-only Class.OpportunityLineItemHelper.checkChangeQuantity: line 11, column 1
public static void checkChangeQuantity(Map<Id, OpportunityLineItem> oldMap, Map<Id, OpportunityLineItem> newMap) {
for (OpportunityLineItem newItem : newMap.values()) {
OpportunityLineItem oldItem = oldMap.get(newItem.Id);
if (newItem.Quantity > oldItem.Quantity) {
Trigger.newMap.get(newItem.Id).addError(System.Label.IncreaseQuantityError);
}
else if (newItem.Quantity < oldItem.Quantity) {
newItem.ServiceDate = Datetime.now().date();
}
}
}
public static List<Opportunity> checkItemChange(Map<Id, OpportunityLineItem> oldMap, Map<Id, OpportunityLineItem> newMap) {
Set<Id> opportunityIdSet = new Set<Id>();
for (OpportunityLineItem newItem : newMap.values()) {
OpportunityLineItem oldItem = oldMap.get(newItem.Id);
if ((newItem.Quantity != oldItem.Quantity) || (newItem.UnitPrice != oldItem.UnitPrice)) {
opportunityIdSet.add(newItem.opportunityId);
}
}
List<Opportunity> opportunityList = [
SELECT Id, StageName
FROM Opportunity
WHERE Id IN: opportunityIdSet
AND StageName <> 'Prospecting'
];
for (Opportunity opp : opportunityList) {
opp.StageName = 'Prospecting';
}
return opportunityList;
}