You need to sign in to do that
Don't have an account?
HELP PLEASE! Apex and Validate
Hi!
I need to add gift cards to an opportunity if the checkbox is enabled, otherwise it will throw an error. In this case, the entered card is deactivated. In the future, I don't have the ability to change any of the opportunity field as the validation fires. How can I solve this problem?
public class OpportunityTriggerHandler {
public void afterInsert (List<Opportunity> newOpportunities){
List<String> cardNames = new List<String>();
for(Opportunity oppItem : newOpportunities) {
cardNames.add(oppItem.Gift_Card__c);
}
List<Gift_Card__c> giftCardToUpdate = [SELECT Active__c, Amount__c, Name
FROM Gift_Card__c
WHERE Name IN :cardNames];
for(Gift_Card__c giftCard: giftCardToUpdate ) {
giftCard.Active__c = false;
}
update giftCardToUpdate;
}
public void beforeInsert (List<Opportunity> newOpportunities){
List<String> cardNames = new List<String>();
for(Opportunity oppItem : newOpportunities) {
cardNames.add(oppItem.Gift_Card__c);
}
List<Gift_Card__c> allGiftCards = [SELECT Active__c, Amount__c, Name
FROM Gift_Card__c
WHERE Name IN :cardNames];
for (Opportunity newOpp: newOpportunities) {
for(Gift_Card__c giftCard: allGiftCards ) {
if (giftCard.Active__c == true) {
newOpp.Amount -= giftCard.Amount__c;
} else {
newOpp.Gift_Card__c.addError('Gift Card is inactive');
}
}
}
}
}
All Answers
can you please elaborate your concern little bit more so we can help you much easily... Because am seeing you have already written some code...
Thanks,
Maharajan.C
Please use the below code which is bulkified. If there is any syntax issue please fix it.
1. Check did you have any validation rule or trigger whihc is blocking your opportunity edit because the above code will fire only in opportunity insert. ( I assumed this trigger will fires only on opp insert based on your naming conditions).
2. To lock the Gift_Card__c field use validation rule.
Please let me know if you need any help...
Thanks,
Maharajan.C
Wilko Survey tends to get honest feedback, reviews, and suggestions from their recent customers and implements them to improve its services.
https://takesurveyz.onl/yourwinningthoughts-com/