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
nikita dhamalnikita dhamal 

trigger on order object when checkbox on account is checked

I want to show  error and order will not be allowed to be created if there is a hard block on the account object is checked.
no error but hte trigger is not working.
my trigger is:

 trigger ValidateOrder on Order (before insert) {
   
    for(Order occ : Trigger.new){
    if(occ.id!=null)
    {
   occ = [Select Accountid from Order where id =: occ.id];
    system.debug('***********************'+occ);
    Account acc = [Select id,Hard_Block__c from Account where  id=:occ.Accountid];
    system.debug('***********************'+acc);
       if(acc.Hard_Block__c == True)
       occ.addError(' This Order Cannot be created' );
    }
    }
}
Best Answer chosen by nikita dhamal
JethaJetha
Hi Nikita,

Please try below code :
trigger ValidateOrder on Order (before insert) 
{
   for(Order occ : Trigger.new)
   {
		Account acc = [Select id,Hard_Block__c from Account where  id=:occ.Accountid];
		if(acc.Hard_Block__c == True)
		occ.addError(' This Order Cannot be created' );
   }
}

 

All Answers

JethaJetha
Hi Nikita,

Please try below code :
trigger ValidateOrder on Order (before insert) 
{
   for(Order occ : Trigger.new)
   {
		Account acc = [Select id,Hard_Block__c from Account where  id=:occ.Accountid];
		if(acc.Hard_Block__c == True)
		occ.addError(' This Order Cannot be created' );
   }
}

 
This was selected as the best answer
Pankaj_GanwaniPankaj_Ganwani
Hi Nikita,

It's not a best practice to write SOQL in for loop as this will hit the governer limit of 100 SOQLs in one transaction if more than 100 records will be imported in Order object and will lead to failures. Please find the below mentioned code:
 
trigger ValidateOrder on Order (before insert) 
{
   Set<Id> setAccId = new Set<Id>();
   for(Order occ : Trigger.new)
   {		
		if(occ.AccountId!=NULL)
			setAccId.add(occ.AccountId);
   }
   
   Map<id, Account> mapIdToAcc = new Map<Id,Account>([select Id from Account where Hard_Block__c = true AND AccountId IN : setAccId]);
   
   for(Order occ : Trigger.new)
   {
		if(occ.AccountId!=NULL && mapIdToAcc.containskey(occ.AccountId))
			occ.addError('This Order Cannot be created');
   }
}

 
saikat sarkarsaikat sarkar
Hi Nikita,
First: You are using Before Insert and checking for Id of Order, as the Id of order will not be available because it has not been created yet. Hence your code will never get executed.
Second: What is the need of "occ = [Select Accountid from Order where id =: occ.id];" as you have the date already in occ.
Third: Never write SOQL in for loop. Try Sets for fetching the Account Ids in your Loop and the query on the set to get the Account Detail.

Hope this helps.