3

New to writing triggers, I'm trying to set one up that adjusts a field on existing records with the same Owner as the one(s) being inserted.

I have an End Date field that I want populated when a new record is inserted, but I don't want to populate the inserted record's End Date.

Am I on the right track with the before insert, or should this be after? And should I be doing an update DML operation at the end?

trigger Task_End_Date on Tasks__c (before insert) {
    Set<Id> task_owners = new Set<Id>();

    for (Tasks__c o : Trigger.new) {
        task_owners.add(o.OwnerId);
    }

    List<Tasks__c> other_tasks = [SELECT Id, OwnerId, End_Date__c
                                  FROM Tasks__c
                                  WHERE OwnerId IN :task_owners];

    for (Tasks__c open_tasks : other_tasks) {
        if (open_tasks.End_Date__c == null) {
            open_tasks.End_Date__c = datetime.now();
        }
    }
}
2

Typically you would use an after update trigger to work with data that is external to the record being updated. In this case however there isn't a dependency on the Tasks__c record having an Id set to update the other records.

Also, by using the before insert trigger you won't risk selecting the record that you just inserted.

For each Tasks__c where you set the End_Date__c you will need to perform a DML update operation.

trigger Task_End_Date on Tasks__c (before insert) {
    Set<Id> task_owners = new Set<Id>();

    for (Tasks__c o : Trigger.new) {
        task_owners.add(o.OwnerId);
    }

    List<Tasks__c> other_tasks = [SELECT Id, OwnerId, End_Date__c
                              FROM Tasks__c
                              WHERE OwnerId IN :task_owners and
                                End_Date__c = null];

    if(other_tasks.size() > 0) {
        for (Tasks__c open_tasks : other_tasks) {
            // Moved the End_Date__c null check into the SOQL query
            open_tasks.End_Date__c = datetime.now();
        }
        update other_tasks;
    }
}
  • Thanks! I thought I needed the DML but was getting confused on a few examples. – user3044 Jun 13 '13 at 20:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.