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
Amit Khanduri.Amit Khanduri. 

I want to create a trigger which can restrict creating opportunity when related account industry is defined

Here we go ...

trigger o1 on Opportunity (Before Insert) {

for(Opportunity o:Trigger.new){
    ID aid = o.Account.ID;
Account a = [Select Name,Industry From Account WHERE ID = :aid];

if(a.Industry == 'Education'){
o.addError('No more Opportunity from Education Domain');
}
}
}

Above triggere is not allowing me to create opportunity for any account.
Best Answer chosen by Amit Khanduri.
Mahesh DMahesh D
Hi Amit,

Please check the below code:
 
trigger OppTrigger on Opportunity (Before Insert) {

	Set<Id> accIdSet = new Set<Id>();
	for(Opportunity opp:Trigger.new){
		if(opp.AccountId != null )
			accIdSet.add(opp.AccountId);
	}
	
	Map<Id, Account> accMap = new Map<Id, Account>([Select Id, Industry, Name from Account where Id IN: accIdSet AND Industry = 'Education']);
	
	for(Opportunity opp:Trigger.new) {
		if(accMap.get(opp.AccountId) == null){
			opp.addError('No more Opportunity from Education Domain');
		}
	}
}

Regards,
Mahesh

All Answers

Amit Khanduri.Amit Khanduri.
Below is the error..

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger AmitKhanduri602.o1 caused an unexpected exception, contact your administrator: AmitKhanduri602.o1: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.AmitKhanduri602.o1: line 5, column 1
Mahesh DMahesh D
Hi Amit,

Please check the below code:
 
trigger OppTrigger on Opportunity (Before Insert) {

	Set<Id> accIdSet = new Set<Id>();
	for(Opportunity opp:Trigger.new){
		if(opp.AccountId != null )
			accIdSet.add(opp.AccountId);
	}
	
	Map<Id, Account> accMap = new Map<Id, Account>([Select Id, Industry, Name from Account where Id IN: accIdSet AND Industry = 'Education']);
	
	for(Opportunity opp:Trigger.new) {
		if(accMap.get(opp.AccountId) == null){
			opp.addError('No more Opportunity from Education Domain');
		}
	}
}

Regards,
Mahesh
This was selected as the best answer
Doug Beltowski XDoug Beltowski X
Hello Amit

The error "System.QueryException: List has no rows for assignment to SObject:" means that your SOQL query is not returning any records. So either your Opportunity doesn't have an Account, or the way you are getting the Id isn't quite working.

As a side note, the way you have written the Trigger is not Bulkified (never put a SOQL query inside a for loop) and could cause issues during bulk uploads. 

I suggest you look at @Mahesh's solution for how to proceed.
Amit Khanduri.Amit Khanduri.
Thanks Mahesh & Doug.... 
if(accMap.get(opp.AccountId) != null){