I'm getting an error when saving the following trigger (it's my first). It says that on line 38, the variable gcamount does not exist. This makes me think that the scope of the variables within the if statement is not broad enough. I then tried declaring the variable outside the for loop but then got an error the first time I tried declaring the gcamount variable saying it's a duplicate. So, how can I declare this variable and make it accessible throughout the code where I can both set and alter the value? I've tried using the public keyword but received errors. Any ideas? Thanks.
trigger GiftCertDonation on Opportunity (after insert, after update) {
//SOQL to return a list of gift certificates whose balance is greater than zero
list<Journal__c> giftcertlist = [SELECT Gift_Certificate_Code__c, Journal_Gift_Card_Usages__c, CreatedById FROM Journal__c WHERE Journal_Type__c = 'Gift Card' AND Gift_Card_Balance__c > 0];
//Convert the list into a map
map<string, string> mymap = new map<string, string>();
for (Journal__c g :giftcertlist){
mymap.put(g.Gift_Certificate_Code__c, g.Journal_Gift_Card_Usages__c);
}
//declared list of ops to later insert
list<Opportunity> lstgcusToInsert = new List<Opportunity>();
for (Opportunity o : trigger.new){
//Is the opportunity in question have a gift certificate as one of the payment methods?
if ((o.Pay_Method__c == 'Gift Certificate') | (o.Pay_Method__c == 'Multiple Methods' & (o.Multiple_Methods_1__c == 'Gift Certificate' | o.Multiple_Methods_2__c == 'Gift Certificate' )) && o.CreatedById !== '**********' ){
//Does the gift certifiacte code refer to a gift certificate with a
if(mymap.contains(o.Gift_Certificate__c)){
//Depending on the payment method, set the gcamount
if (o.Pay_Method__c == 'Gift Certificate'){
decimal gcamount = o.Amount;
}
else if (o.Multiple_Methods_1__c == 'Gift Certificate'){
decimal gcamount = o.Multiple_Methods_Amount_1__c ;
}
else if (o.Multiple_Methods_2__c == 'Gift Certificate'){
decimal gcamount = o.Multiple_Methods_Amount_2__c ;
}
//Create New Gift Card Usage
Gift_Card_Usage__c gcu = new Gift_Card_Usage__c();
gcu.Journal_Gift_Card_Usage__c = mymap.get(o.Gift_Certificate__c) ;
gcu.Amount_Used__c = gcamount;
//add to list
lstgcusToInsert.add(gcu); *****LINE 38 - WHERE THE ERROR EXISTS*****
}
}
}
if(lstgcusToInsert.size() > 0) {
insert lstgcusToInsert;
}
}