+ Start a Discussion
sreekanth reddysreekanth reddy 

Record Type IN Apex Trigger

Hi All,

How to Exclude one opportunity record type in below trigger.

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){
                List<Invoice__c> lstBatAlt =[select id,Opportunity1__c,Name from Invoice__c
                                             where Opportunity1__c IN:Opportunity ];
                    cb.addError('You cannot create more than two receipts for opportunity');

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){
			List<Invoice__c> lstBatAlt =[select id,Opportunity1__c,Name 
			                             from Invoice__c
										 where Opportunity1__c IN:Opportunity and Opportunity1__r.recordType.developerName != 'Recordtypename' ];
				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