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
Suneel B 9Suneel B 9 

create opportunity for an account record if activate field in account is YES and if its blank or no than it has to throw an error.

Hello guys, i am trying to create an opportunity for an account record only if the acoount record active is YES  and if active is no or the field is blank it has to throw an error. Below is the code, can you pelase help me out,

trigger oppactive on Opportunity (before insert) 
{
   set<id> accid = new set<id>();
   List<Opportunity> opp = trigger.new;
   Integer i;
   for(opportunity opp1:opp)
   {
     accid.add(opp1.Accountid);
     system.debug('Test 1'+accid);
   }
   List<opportunity> opp3 =  [select id, Name, opportunity.Accountid, opportunity.Account.Active__c from Opportunity where Accountid in: accid];
     for(opportunity opp2:opp3)
   {
      system.debug('Enter loop'+opp2);
      if(opp2.Account.Active__c =='No')
      {
        Trigger.new[0].adderror('Account must be active before creating an account');
        system.debug('test3'+opp2);
      }    
    }  
}
Best Answer chosen by Suneel B 9
Neetu_BansalNeetu_Bansal

Hi Suneel,

You are querying on Opportunity, but the triggers fires on before insert, so it will not return the Opportunity which is not yet inserted. Use the below code:
trigger oppactive on Opportunity( before insert ) 
{
	Set<Id> accid = new Eet<id>();
	for( Opportunity opp1 : trigger.new )
	{
		accid.add( opp1.Accountid );
		system.debug('Test 1'+accid);
	}

	Map<Id, Account> accountMap = new Map<Id, Account>([ Select id, Name, Active__c from Account where Id IN: accid ]);
    for( Opportunity opp1 : trigger.new )
	{
		system.debug('Enter loop'+opp1);
		if( opp1.AccountId != null && accountMap.containsKey( opp1.AccountId )
			&& ( accountMap.get( opp1.AccountId ).Active__c == null
				|| accountMap.get( opp1.AccountId ).Active__c == ''
				|| accountMap.get( opp1.AccountId ).Active__c =='No' )
		)
		{
			opp1.adderror('Account must be active before creating an Opportunity');
			system.debug('test3'+opp1);
		}    
    }  
}
If this post helps, mark this as best answer so will help others in future.

Thanks,
Neetu