Hello and thanks in advanced.
-Background-
I have a custom object for files, one of the files recorded in this object needs to be the primary file, but only one.
-Approach-
Create a trigger that checks before the new insert if there is another record already mark as primary, if so show a warning, otherwise insert the record.
-Problem-
I'm new to Apex code, to triggers and everything. So, not sure why this is not working. When I'm creating a new record and check the primary file checkbox it doesn't creates the record. So I'm unable to see if the trigger worked.
-Code-
trigger trg_Custom_Object on Custom_Object__c (before insert) {
Set <Id> filesId = new Set <Id>();
List <Custom_Object__c> filesToSave = new List <Custom_Object__c>();
for (Custom_Object__c files : Trigger.new) {
//Check if trigger.new Primary_file__c is TRUE
if (files.Primary_file__c){
//Add the Id to a list of ids
filesId.add(files.Id);
filesToSave.add(files);
}
}
//Query the ids from object where Primary_file__c is TRUE and is old
List <Custom_Object__c> filesList = new List <Custom_Object__c> ([select id from Custom_Object__c where Primary_file__c = true and id not in :filesID] );
for (Custom_Object__c files : Trigger.new) {
//For each new record to be inserted check if its Primary_file__c is set to TRUE
//and if there is already a file with Primary_file__c set TRUE
if (files.Primary_file__c && filesList.size() > 0){
//Trhows error
files.Id.AddError('You cannot have more than one primary file');
} else {
//Insert new record
//insert filesToSave; (Commented by @dschach because unnecessary.)
}
}
}
insert
within an insert trigger of the same object. BTW: avoid insert in a loop