+ Start a Discussion
Nertin HoxhaNertin Hoxha 

Help Bulkifying this before-Trigger with error-message.

trigger DuplicateService on Site__c (before insert) {
    for(Site__c  B : Trigger.New) {
        try {
            Integer i = [SELECT count() FROM Site WHERE Account__c = :B.Account__c AND RecordTypeId = :B.RecordTypeId];

            if (i > 0) {
            String RT = [SELECT Name FROM RecordType WHERE Id = :B.RecordTypeId].Name;
            String TS = [SELECT Name FROM Site__c WHERE Account__c = :B.Account__c AND RecordTypeId = :B.RecordTypeId].Name;
               B.addError('Already existing ' + RT + ': <<<' + TS + '>>>, !!');
            }
        }
        catch (DmlException e) {
            System.debug('Trigger DuplicateService: ' + e.getMessage());
        }
    }
}

 
Best Answer chosen by Nertin Hoxha
Amit Chaudhary 8Amit Chaudhary 8
Try to update your code like below
trigger DuplicateService on Site__c (before insert) 
{

	Map<ID,RecordType> mapRecordType = new Map<ID,RecordType>([SELECT Name FROM RecordType]);

	Set<String> setRecordTypeId = new Set<String>();
	Set<String> setAccountId = new Set<String>();
	
    for(Site__c  B : Trigger.New) 
	{
		setRecordTypeId.add(B.RecordTypeId);
		setAccountId.add(B.Account__c);
	}
	
	List<Site__c> lstSite = [ select id,Account__c,RecordTypeId,Name from Site__c WHERE Account__c = :setAccountId AND RecordTypeId = :setRecordTypeId ]
	Map<String,Site__c> mapAccAndRecordTypeWiseSite = new Map<String,Site__c>();
	
	For(Site__c B :lstSite)
	{
		String Key = B.Account__c+'_'+B.RecordTypeId ;
		mapAccAndRecordTypeWiseSite.put(Key,B);
	}

    for(Site__c  B : Trigger.New) 
	{
		String Key = B.Account__c+'_'+B.RecordTypeId ;
        try 
		{
            if (mapAccAndRecordTypeWiseSite.containsKey(Key)) 
			{
				B.addError('Already existing ' + mapRecordType.get(B.RecordTypeId).Name + ': <<<' + mapAccAndRecordTypeWiseSite.get(Key).Name + '>>>, !!');
            }
        }
        catch (DmlException e) 
		{
            System.debug('Trigger DuplicateService: ' + e.getMessage());
        }
    }
}
Let us know if this will help you