I am trying create a Trigger in my Salesforce Org, where I want to create a new record in an object only if no records already exists, and if records already exist then the end date should be null.
If there are records with end date values then the new record can be created. hope this is not too confusing. I have created the following code. This code creates a new record even though the end date has a date in the existing record.
trigger CreateGADeclarationRecord on GA_Declaration__c (before insert) {
// Query existing records with blank End Date
List<GA_Declaration__c> existingRecords = [
SELECT Id, End_Date__c
FROM GA_Declaration__c
WHERE End_Date__c = NULL OR End_Date__c = ''
];
if (existingRecords.isEmpty()) {
insert newRecord;
} else {
// Prevent the insert
for (GA_Declaration__c newRecord : Trigger.New) {
newRecord.addError('Cannot create a new record. Existing records found with non-blank End Date.');
}
}
}
The End_Date__c = ''
in the where clause throws an error, so I removed it while testing, and only used the null
criteria. I think the problem is in the select statement, it is not correctly identifying the already existing records.
insert
the same records that you're processing in abefore insert
trigger (nor in anafter insert
trigger).GA_Declaration__c
records related to another type of SObject? Are they occasionally deleted by some other process (if not, then your trigger would always result in an error except for the very first time you insert records in your org).