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
msvrad10msvrad10 

Help with Trigger to limit number of Related records

I am trying to write a trigger that will error if an account already has 2 related records from a custom object (Entity Account). Users are only allowed to create the related records through the related list on the account page. I am wondering what a trigger that would limit the number of records that can be created would look like. Any suggestions would greatly be appreciated.

 

Thanks in advance!

Best Answer chosen by Admin (Salesforce Developers) 
sravusravu

If your have a lookup relationship use the following code:

 

trigger RelatedRecordsTrigger on Test_Object__c (before insert) {

            Integer count = [select count() from Test_Object__c where Account__c=:Trigger.new[0].Account__c];     

           System.debug('****'+count);

           if(count>=2){

                       Trigger.new[0].addError('There are already two records existing with this account');

          }

}

 

Please accept this as a solution if this resolves your issue.

All Answers

sravusravu

If I am not wrong in understanding your scenario, I created a custom object Test_Object__c which has a master-detail relationship with the Account object and we can create Test_Object__c records from Account Object.

As per the code, when users try to create more than two records from the Account object related list, the following code triggers an error saying that there are already two records created under this account.

 

Trigger RelatedRecordsTrigger on Test_Object__c (before insert) {    
    Integer count = [select count() from Test_Object__c];    
    if(count>=2){            
        Trigger.new[0].addError('There are already two records existing with this account');   
        }
}

 

Correct me if I am wrong in understanding your scenario.

Please accept this as a solution if this resolves your issue.

msvrad10msvrad10

The related object "Test_Object__c" was created with a lookup field to the Account object. There is not a master-detail relationship. Does that make a difference?

 

sravusravu

If your have a lookup relationship use the following code:

 

trigger RelatedRecordsTrigger on Test_Object__c (before insert) {

            Integer count = [select count() from Test_Object__c where Account__c=:Trigger.new[0].Account__c];     

           System.debug('****'+count);

           if(count>=2){

                       Trigger.new[0].addError('There are already two records existing with this account');

          }

}

 

Please accept this as a solution if this resolves your issue.

This was selected as the best answer