trigger validateCategoryOnBankAccount on Bank_Account__c(before insert, before Update) {
Set <Id> doctorIds = new Set <Id> ();
set <string> picval = new set <string> ();
if (trigger.isInsert) {
for (Bank_Account__c bank: trigger.new) {
if (bank.Category__c != null && bank.Doctor__c != null) {
doctorIds.add(bank.Doctor__c);
picval.add(bank.Category__c);
}
}
}
if (trigger.IsUpdate) {
for (Bank_Account__c bank: trigger.new) {
if (bank.Category__c != null && bank.Doctor__c != null) {
if (bank.Category__c != trigger.oldmap.get(bank.id).Category__c) {
doctorIds.add(bank.Doctor__c);
picval.add(bank.Category__c);
}
}
}
}
if (doctorIds != null && doctorIds.size() > 0) {
list < Bank_Account__c > banklist = [select Id, Name, Doctor__c, Category__c from Bank_Account__c where Doctor__c in: doctorIds AND Category__c =: picval];
if (banklist.size() > 0) {
for (Bank_Account__c bank: trigger.new) {
bank.addError('Bank Account with this category exists!');
}
}
}
}
Sign up
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
|
||||
|
Yes and no No need for seperate block for Also
This is not bulkified. According to this logic, if even one record causes this code to be entered then ALL records will have the error added to them without regard to the specific record that you are actually trying to throw the error for Without much thought about it this may achieve what you want for the last part
There are certainly better ways do do this and rewrite the whole trigger though, I just do not have the bandwidth to put into it at the moment. |
|||||||||||||||||||||
|
There's a lot better way to code your intent than you've done here. Here's an alternative (untested):
This also prevents duplicate bank accounts that may occur when a bank account is deleted, another is created, and then the first is subsequently undeleted. All of the extra work checking if doctor/category has already changed is eliminated for the cost of a single extra query. In practice, this shouldn't have much of an effect on performance. |
|||||
|