When I write an update trigger on Task which update other Task record.

If I don't check the difference between oldMap and new, the trigger will run infinitely.

So I want to add an if statement so if any of the field's value of oldMap is different from that of new, the update happens.

There are lots of fields on Task, how can I use a reflection to loop through the feilds' values of oldMap and new ?

  • Your scenario is confusing to me. Is the task trigger updating its sibling tasks or child tasks or something else? I don't see a reason why it should fall into infinitely loop. And if it falls into, I don't see a reason your approach is helping with that.
    – Lance Shi
    Apr 2 '15 at 3:31

From what I understood, you want to be able to check whether a field value is different in trigger.old and trigger.new for a record in your after trigger and only in that case you want to process that record.

In order to achieve that you'll need to dynamically get the list of all fields on the task record and check for each one of those for changes. The code below will illustrate roughly how that can be done. I haven't tested it and wrote it on the go, so you might need to do some tweaking before you get it working:

trigger TaskTrigger on Task (after insert) 
    // Get all the task fields 
    Map <String, Schema.SObjectField> taskFieldsMap = schema.SObjectType.Task.fields.getMap();
    List <Schema.SObjectField> taskFields = taskFieldsMap.values();
    List <String> taskAPIFieldNames = new List <String> ();

    // Go through all the task fields 
    for (Schema.SObjectField s : taskFields)
        // Put the task API name field in a list

    // For each task in the trigger
    for (sObject taskRecord : trigger.new)
        // For each field
        for(String field : taskAPIFieldNames)
            // Check whether new value != than old value for the same record
            if (taskRecord.get(field) != trigger.oldMap.get((Id)taskRecord.get(Id)).get(field))
                // Whatever you want to do with the record, the field values for this field are different

Each step is explained in the comments and it should give you the idea of how to approach this.

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.