Good day, everyone. I have started learning Apex. And need help with triggers. The problem is: I have custom object Gift Card, which is not related to any other objects. On Opportunity I have custom text field Gift Card. While inserting name of gift card I need to check if this card is active, if not I should show some error. If card is active I need to substract amount of card from amount of Opportunity. But using this code I always see only error message, it doesn't matter if card is active or not.
trigger cardFromOpportunity on Opportunity (before insert, before update) {
for(Opportunity opp : Trigger.new){
for(Gift_Card__c card:[SELECT Name,Amount__c,Active__c FROM Gift_Card__c]){
if(opp.Gift_Card__c == card.Name && card.Active__c == true){
opp.Amount -= card.Amount__c;
card.Active__c = false;
update card;
}else if(opp.Gift_Card__c == card.Name && card.Active__c == false){
opp.Gift_Card__c.addError('Error');
}
}
}
}