You need to sign in to do that
Don't have an account?
msvrad10
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!
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
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?
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.