1

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.

3
  • I think that going into more detail about the conditions you're trying to work with is important. Your words also contradict your code (you say you can insert records with a blank end date, but your code says you reject everything if there's an existing record). You don't (or rather, can't) insert the same records that you're processing in a before insert trigger (nor in an after insert trigger).
    – Derek F
    Commented May 11 at 14:34
  • Are these 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).
    – Derek F
    Commented May 11 at 14:34
  • Thanks Derek for the comments, Sorry for the confusion my words have created. My criteria is this, 1. Create a new record only if end dates in the already existing records are not blank. 2. Create a new record if no records already exists in the object as well, 3. the new record can have a blank end date. I am new to Apex,. Commented May 11 at 15:28

2 Answers 2

0

You have several problems. First, you're looking for records where End_Date__c is null, and then adding an error if there are any records. This is different than your stated intent that you want to allow a new record only if all records have a null End_Date__c. Further, you're already in an insert operation, so you don't need to insert again. Rather, you just need to not add an error. You also haven't considered the possibility that two or more records inserted at approximately the same time may cause a problem. As such, you need to also consider row locking, which means using an after insert trigger.

Here's my proposed not-ready-for-production revision:

trigger CreateGADeclarationRecord on GA_Declaration__c (after insert) {
    // Check for an existing record
    GA_Declaration__c[] existingRecords = [
        SELECT  Id
        FROM    GA_Declaration__c
        WHERE   End_Date__c <> NULL AND
                Id <> :Trigger.new
        LIMIT   1
        FOR UPDATE
    ];
    // Check for bulk insert of records
    Integer matchingRecords = 0;
    for(GA_Declaration__c newRecord: Trigger.new) {
        if(newRecord.End_Date__c != null) {
            matchingRecords++;
        }
    }
    for(Integer i = Trigger.size - 1; i >= 0; i--) {
        if(
            !existingRecords.isEmpty() && Trigger.new[i].End_Date__c != null || // Preexisting non-blank date
            matchingRecords > 1 && Trigger.new[i].End_Date__c != null // More than 1 record in this batch
        ) { 
            Trigger.new[i].addError('Cannot create a new record. Existing records found with non-blank End Date.');
            matchingRecords--;
        }
    }
}

You should, however, be using some kind of trigger framework.

2
  • Hi sfdcfox, thanks for the comments. Sorry for the confusion in the working of the problem. You have rightly summarised it. - First, you're looking for records where End_Date__c is null, and then adding an error if there are any records'. - These are the criteria for new records. 1. no records already exist with blank end dates. 2. no records already exists 3. new records can have blank end date. I have tested your code it keeps adding new records, it should have stopped creating the second record because I put the first record with end date blank. Commented May 11 at 15:36
  • To add to my comments above, the idea is there can be only one record with blank end date at any time. New records are created very rarely,, so there is not going to be any bulk insert. Commented May 11 at 15:52
-1

try below code:

trigger CreateGADeclarationRecord on GA_Declaration__c (before insert) {
    List<GA_Declaration__c> existingRecords = [SELECT Id, End_Date__c FROM GA_Declaration__c];
    
    Boolean canCreateNewRecord = existingRecords.isEmpty();

    if (!canCreateNewRecord) {
        canCreateNewRecord = true;
        for (GA_Declaration__c record : existingRecords) {
            if (record.End_Date__c != null) {
                canCreateNewRecord = false;
                break;
            }
        }
    }

    if (!canCreateNewRecord) {
        for (GA_Declaration__c rec : Trigger.new) {
            rec.addError('A new record cannot be created in GA_Declaration__c because there are existing records with a non-null End_Date__c.');
        }
    }
}
2
  • Code dumps make for poor answers. The explanation is as important as the solution itself. How does your proposed code differ from what OP already has? Why do those differences matter? Edit your answer to include a detailed explanation.
    – Derek F
    Commented Jun 13 at 12:50
  • One glaring issue with this attempt is the query at the beginning with no filters. This will eventually be a problem for query selectivity, but you'd probably run into the 50k query row governor limit before that. Even a moderate number of records could cause problems for someone using this code (You would run into an error if you're trying to insert 1000 records if there are 10,001 existing GA_Declaration__c records).
    – Derek F
    Commented Jun 13 at 12:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .