function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vikram Singh 157Vikram Singh 157 

Hi Prevent to create Opportunity on the base on account filed value . But this allow to save record

Here Account custom filed id Probhited__c and code is :
trigger ProhibitedOpp1 on Opportunity (before insert) {
   List<Opportunity> opps = [Select Id,Account.Prohibited__c From Opportunity Where Id in : Trigger.new];
    for (Opportunity opp: opps)
    { if (opp.account.Prohibited__c=='Pakistan') {
        opp.adderror('You cannot create an Opportunity from an Account located in a restricted or Pakistan country');
    }
   
    }
Best Answer chosen by Vikram Singh 157
Nayana KNayana K
trigger ProhibitedOpp1 on Opportunity (before insert) {
Set<Id> setAccId = new Set<Id>();
for(Opportunity objOpp : Trigger.New){
    setAccId.add(objApp.AccountId);
}
setAccId.remove(null);

Map<Id, Account> mapAcc = new Map<Id, Account>([Select Id,Prohibited__c From Account Where Id in : setAccId];
    for (Opportunity opp: Trigger.New)
    { if (mapAcc.get(opp.accountId).Prohibited__c =='Pakistan') {
        opp.adderror('You cannot create an Opportunity from an Account located in a restricted or Pakistan country');
    }
   
    }

In trigger,  if we want to refer parent fields values,  we can't do it directly.  We have to perform query. 

All Answers

Nayana KNayana K
trigger ProhibitedOpp1 on Opportunity (before insert) {
Set<Id> setAccId = new Set<Id>();
for(Opportunity objOpp : Trigger.New){
    setAccId.add(objApp.AccountId);
}
setAccId.remove(null);

Map<Id, Account> mapAcc = new Map<Id, Account>([Select Id,Prohibited__c From Account Where Id in : setAccId];
    for (Opportunity opp: Trigger.New)
    { if (mapAcc.get(opp.accountId).Prohibited__c =='Pakistan') {
        opp.adderror('You cannot create an Opportunity from an Account located in a restricted or Pakistan country');
    }
   
    }

In trigger,  if we want to refer parent fields values,  we can't do it directly.  We have to perform query. 
This was selected as the best answer
Vikram Singh 157Vikram Singh 157
Thanks A lot Miss. Nayana K.
Nayana KNayana K
Welcome :)