You need to sign in to do that
Don't have an account?
System.ListException: List index out of bounds: 0:
Apex trigger StudentInsertMaxLimit caused an unexpected exception, contact your administrator: StudentInsertMaxLimit: execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0: Trigger.StudentInsertMaxLimit: line 12, column 1
code:
trigger StudentInsertMaxLimit on Student__c (before insert) {
if(Trigger.isInsert)
{
for(Student__c stu:Trigger.new)
{
list<Student__c> stuList=[select Class__r.NumberOfStudents__c,Class__r.MaxSize__c from student__c where id=:stu.id];
if(Integer.Valueof(stuList.get(0)) == Integer.Valueof(stuList.get(1)))
{
stu.addError('Maximum limit of students in a class is reached');
}
}
}
}
All Answers
Hi
stu.addError('Maximum limit of students in a class is reached');
just change this line
stuList[o].addError('Maximum limit of students in a class is reached');
Try this,
One more thing, You are quering using id, so you must write after insert trigger. Because it will not work with before insert.
Error: Compile Error: Expression must be a list type: SOBJECT:Student__c at line 12 column 21
i got following error.
Apex trigger StudentInsertMaxLimit caused an unexpected exception, contact your administrator: StudentInsertMaxLimit: execution of AfterInsert caused by: System.FinalException: SObject row does not allow errors: Trigger.StudentInsertMaxLimit: line 17, column 1
Hi Dhaval Panchal,
still i got same error.but i modified some of things then it worked fine.
trigger StudentInsertMaxLimit on Student__c (after insert) {
Student__c stud=Trigger.new[0];
Set<ID> setStudentId = new Set<ID>();
if(Trigger.isInsert)
{
for(Student__c stu:Trigger.new)
setStudentId.add(stu.Id);
}
if(setStudentId.size()>0)
{
list<Student__c> stuList=[select Class__r.NumberOfStudents__c,Class__r.MaxSize__c from student__c where id In:setStudentId];
if(stuList.size()>0)
{
for(Student__c std:stuList)
{
if(std.Class__r.NumberOfStudents__c >= std.Class__r.MaxSize__c)
{
stud.addError('Maximum limit of students in a class is reached');
}
}
}
}
}