+ Start a Discussion
Nertin HoxhaNertin Hoxha 

How can i bulkify this before trigger without hitting governor's limits?

trigger DuplicateService on Site__c (before insert) {
    for(Site 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
Hi Nertin,

Please try below code
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());
        }
    }
}
Trigger Best Practices | Sample Trigger Example | Implementing Trigger Framework

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail


Let us know if this will help you
 

All Answers

GauravGGauravG
Nertin,

You can refer below code:
 
trigger testLoadTestA on TestA__c (before insert) {
    List<String> lstName = new List<String>();
    for(TestA__c s : Trigger.new) {
        lstName.add(s.name);    
    }    
    System.debug('lstName : ' + lstName);
    testATrigger.validateRecord(lstName);
}


public class testATrigger {
    public testATrigger() {
    }   
    public static void validateRecord(List<String> lstStrNewName) {    
        System.debug('lstStrNewName : ' + lstStrNewName);
        Integer i = [SELECT Count() FROM TestA__c WHERE Name = : lstStrNewName];
        if(i>0) {
            System.debug('Count of SOQL : ' + i );
        }    
    }
}

Instead of calling controller method from trigger, you can directly use the code in trigger itself.
Nertin HoxhaNertin Hoxha
thank you Gaurav, but trigger still not working!
Amit Chaudhary 8Amit Chaudhary 8
Hi Nertin,

Please try below code
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());
        }
    }
}
Trigger Best Practices | Sample Trigger Example | Implementing Trigger Framework

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail


Let us know if this will help you
 
This was selected as the best answer
Nertin HoxhaNertin Hoxha
Thank You Amit. I'm doing the transition from admin to dev. Cheers!