You need to sign in to do that
Don't have an account?
Maruti Patil 14
I am writing trigger on junction object to limit only 5 authors per research paper.Research_paper__c and Author__c having MD with with Author_Research_Paper__c.Below is my code but i am new to salesforce and i am unable to find the error.
trigger AuthorResearchPaperTrigger on Author_Research_Paper__c (before insert) {
switch on trigger.operationType{
when BEFORE_INSERT{
Set<id> researchPaperIdSet = new Set<id>();
Set<id> authorIdSet = new Set<id>();
for(Author_Research_Paper__c authRePaperObj : trigger.new){
if(authRePaperObj.Research_Paper__c != null){
researchPaperIdSet.add(authRePaperObj.Research_Paper__c);
}
if(authRePaperObj.Author__c != null){
authorIdSet.add(authRePaperObj.Author__c);
}
}
List<Author_Research_Paper__c> authorResearcPaperList = [SELECT id FROM Author_Research_Paper__c WHERE Research_Paper__c IN : researchPaperIdSet AND Author__c IN : authorIdSet];
List<String> researchPaperNameList = new List<String>();
List<String> authorNameList = new List<String>();
for(Author_Research_Paper__c authRePaperObj : authorResearcPaperList){
researchPaperNameList.add(authRePaperObj.Research_Paper__c);
authorNameList.add(authRePaperObj.Author__c);
}
for(Author_Research_Paper__c authRePaperObj : trigger.new){
if(researchPaperNameList.contains(authRePaperObj.Research_Paper__c) && authorNameList.size() > 5){
authRePaperObj.addError('Only 5 Authors are allowed.');
}
}
}
}
}
switch on trigger.operationType{
when BEFORE_INSERT{
Set<id> researchPaperIdSet = new Set<id>();
Set<id> authorIdSet = new Set<id>();
for(Author_Research_Paper__c authRePaperObj : trigger.new){
if(authRePaperObj.Research_Paper__c != null){
researchPaperIdSet.add(authRePaperObj.Research_Paper__c);
}
if(authRePaperObj.Author__c != null){
authorIdSet.add(authRePaperObj.Author__c);
}
}
List<Author_Research_Paper__c> authorResearcPaperList = [SELECT id FROM Author_Research_Paper__c WHERE Research_Paper__c IN : researchPaperIdSet AND Author__c IN : authorIdSet];
List<String> researchPaperNameList = new List<String>();
List<String> authorNameList = new List<String>();
for(Author_Research_Paper__c authRePaperObj : authorResearcPaperList){
researchPaperNameList.add(authRePaperObj.Research_Paper__c);
authorNameList.add(authRePaperObj.Author__c);
}
for(Author_Research_Paper__c authRePaperObj : trigger.new){
if(researchPaperNameList.contains(authRePaperObj.Research_Paper__c) && authorNameList.size() > 5){
authRePaperObj.addError('Only 5 Authors are allowed.');
}
}
}
}
}
The condition authorNameList.size() > 5 should be checking the number of unique authors in the junction object, but it is checking the size of the list which has all authors present in the authorResearcPaperList.