You need to sign in to do that
Don't have an account?
trigger opportunity
Hi, everyone!
Here I need to create trigger that support gift cards which allows users to reduce Opportunity price on fixed amount. Opportunity and Gift Card has no relationship. User has write name of gift card in opportunity then its reduce amount opportunity for the amount of gift card.
public with sharing class GiftCardTriggerHandler {
public void afterUpdate(List<Gift_Card__c> newGiftCards) {
Set<String> opportunityNames = new Set<String>();
for (Gift_Card__c giftCardItem : newGiftCards) {
opportunityNames.add(giftCardItem.Name);
}
Map<ID, Opportunity> opportunitiesToUpdate = new Map<ID, Opportunity>([SELECT Id, Gift_Card__c, Amount FROM Opportunity WHERE Gift_Card__c IN: opportunityNames]);
List<Gift_Card__c> giftCardToInsert = [SELECT Id, Name, Amount__c, Active__c FROM Gift_Card__c WHERE Name IN: opportunityNames];
for(String opportunityName : opportunityNames) {
Decimal Amount = 0;
Opportunity currentOpportunity = opportunitiesToUpdate.get(opportunityName);
System.debug('Null' + currentOpportunity.Amount);
for(Gift_Card__c giftCardItem : giftCardToInsert) {
if(giftCardItem.Name == opportunityName) {
if(giftCardItem.Active__c == true) {
Amount = currentOpportunity.Amount - giftCardItem.Amount__c;
giftCardItem.Active__c = false;
}
else if(giftCardItem.Active__c == false) {
opportunityName.addError('Please, choose active Gift Card!');
}
}
}
if (currentOpportunity.Amount < Amount) {
currentOpportunity.Amount = Amount;
opportunitiesToUpdate.put(opportunityName, currentOpportunity);
}
}
update opportunitiesToUpdate.values();
}
}
As a best practice you should avoid writing Nested Loops.Please find the optimized code.Hope it helps you.
Thanks,
Vijay,
Solution Architect
Steadfast Consultancy Services.
try follwoing code in different way. let me know if it hleps you by marking it as best answer.
Thank you