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
sreekanth reddysreekanth reddy 

Record Type IN Apex Trigger

Hi All,

How to Exclude one opportunity record type in below trigger.
Recordtype='Recordtypename'.

trigger Receiptt on Invoice__c(before insert) {
    ReceiptRestiction__c ua = ReceiptRestiction__c.getInstance (userinfo.getUserId());
    if (ua.Active__c) {
        set<id> Opportunity = new set<id>();
        
        Profile adminId = [SELECT Id from Profile where Name='Accounts' LIMIT 1];
        
        
        if((trigger.isBefore && trigger.isInsert) && UserInfo.getProfileId() != adminId.Id){
            for(Invoice__c cb:System.Trigger.new){
                
                
                Opportunity.add(cb.Opportunity1__c);
                
                List<Invoice__c> lstBatAlt =[select id,Opportunity1__c,Name from Invoice__c
                                             where Opportunity1__c IN:Opportunity ];
                
                if(lstBatAlt.size()>1){
                    
                    cb.addError('You cannot create more than two receipts for opportunity');
                }
            }
            
        }  
        
    }
}

Thanks
Srikanth
Ahmad J. KoubeissyAhmad J. Koubeissy
you are doing a SOQL query inside a for loop. you should not do that, ever.

Please try this code
 
trigger Receiptt on Invoice__c(before insert) {
    ReceiptRestiction__c ua = ReceiptRestiction__c.getInstance (userinfo.getUserId());
    if (ua.Active__c) {
        set<id> Opportunity = new set<id>();
        Profile adminId = [SELECT Id from Profile where Name='Accounts' LIMIT 1];
        
        if((trigger.isBefore && trigger.isInsert) && UserInfo.getProfileId() != adminId.Id){
            for(Invoice__c cb: Trigger.new){
                Opportunity.add(cb.Opportunity1__c);
            }
			List<Invoice__c> lstBatAlt =[select id,Opportunity1__c,Name 
			                             from Invoice__c
										 where Opportunity1__c IN:Opportunity and Opportunity1__r.recordType.developerName != 'Recordtypename' ];
                
			if(lstBatAlt.size()>1){
				cb.addError('You cannot create more than two receipts for opportunity');
			}
        }  
    }
}

You hsould consider that this code wont work properly if you are updating two or more opportunities at the same time (using dataloader for exemple).

if this answer solves your problem, please mark as best answer. thanks