You need to sign in to do that
Don't have an account?
Salsforce trigger addError Method
Hi, I am new to development and and stuck with two different scenario for a trigger on before insert & before update context variables.
SCENARIO 1 - BEFORE INSERT
I have created 2 objects, 1 is for Course and another is Student.
Trigger is on the student object which will check the open vacancies(formula field on course i.e. Total strength - Total no of students(which is again a roll up summary of count of students)) for the course he/she will apply for.
If the open vacancy == 0 then the admin should get error while creating record.
set<Id> courseIds = new set<Id>();
System.debug('Before insert trigger fired');
for(Student__c student : Trigger.New){
courseIds.add(student.Course_Name__c);
}
for(Course__c course : [SELECT Id, Name, Open_Vacancies__c FROM Course__c WHERE Id IN: courseIds]){
if(course.Open_Vacancies__c == 0){
System.debug('Seats are full');
}
}
Please refer the above code snippet I have wrote but the problem is I can not add addError() method on the student record as it is out of for loop. Debug is working fine but also create the record. SInce it is creating record open vacacy is field's value is going in negative but it should not happen until and unless open vacancy > 0.
SCENARIO 2 - BEFORE UPDATE
For this scenario also facing same issue wih addError() method. Here the scenario is to restrict the admin from updating the enrollment no.(field on student object). If the enrollment no is updating then it should give an error message
if(Trigger.isUpdate){
for(Student__c student : Trigger.old){
System.debug('Before Update trigger fired');
if(Trigger.oldMap.get(student.Id).Enrollment_Number__c != Trigger.NewMap.get(student.Id).Enrollment_Number__c){
System.debug('You can not update the enrollment number');
//One way to show error
student.addError('You can not update enrollment number');
//Another way to show error
Student__c record = Trigger.oldMap.get(student.ID);
record.addError('You can not update enrollment number');
}
}
}
Please refer the above code snippet I have wrote here also, debug is working fine, but addError Method is not working.
Thanks.
Can you please use the below code snippet:
For Insert
For Update:
Let me know if you face any issue with this.
Thanks,
Abhishek Bansal.
abhibansal2790@gmail.com
All Answers
Can you please use the below code snippet:
For Insert
For Update:
Let me know if you face any issue with this.
Thanks,
Abhishek Bansal.
abhibansal2790@gmail.com
Thanks Abhishek,
Just have one more query, whenever I was inserting record it also fires the update trigger automatically. How can I prevent that.