You need to sign in to do that
Don't have an account?

Prevent creation of Opportunity based on Account field value
Hi - very new to writing Apex and I'm stumped on this requirement: display an message when user clicks on the New Opportunity button in the Contact record if the Account where it belongs has the Prohibited field set to "Embargoed Country". Below is what I've written so far:
Can somebody please tell me what I need to change/update in my code? Thanks in advance! :)
trigger ProhibitedOpp1 on Opportunity (before insert) { Map<Id,Opportunity> opps = new Map<Id,Opportunity>([Select Id,Account.Prohibited__c From Opportunity Where Id in : Trigger.new]); for (Opportunity opp: trigger.new) { if (opp.account.Prohibited__c=='Embargoed Country') { opp.adderror('You cannot create an Opportunity from an Account located in a restricted or embargoed country'); } } }
Can somebody please tell me what I need to change/update in my code? Thanks in advance! :)
You had queried the account.prohibited__c field and stored the records in Map called opps, however, your were iterating over the records in trigger.new which would not have the account field value.
Let me know if that helps.
You could achieve this using a simple validation rule. I am not sure why you went the apex way.
The validation rule should check ISNEW() on opportunity and also check the related account field value.
Its very simple one. Try it and let me know if it works this way.
Thanks
Srinath R
@terrence_chiu - thanks for the suggested code but it didn't work. I was still able to save an Opp even if the Account is tagged as embargoed.
The user would not even get to the edit page via this method. Adding an error via a trigger would still require the user to save the record first before the error occurs. Let me know if this helps.