1

Requirement: After Task record is created then any update should not happen except contacts change (WhoID). I have written simple code in Before Update Trigger but enable to get the right syntax for copying the changed value from Old Trigger to new Trigger field in if-condition (commented out), (or) how do we get dynamic field Name so that we assign the old value, any help would be greatly appreciated:

Schema.DescribeSObjectResult objSchema = task.sObjectType.getDescribe();
  Map<String, Schema.SObjectField> fieldMap = objSchema.fields.getMap();

  for (Task Tsk: Trigger.new) {
        Task oldTask = Trigger.oldMap.get(Tsk.ID);
        for (String fieldName : fieldMap.keySet()){
            if ((Tsk.get(fieldName) != OldTask.get(fieldName)) && !fieldName.equalsIgnoreCase('WhoId')){
                //Tsk.fieldName = OldTask.get(fieldName);
            }
      }     
  } 
3

The complement to get in this case is put.

record.put(field, oldRecord.get(field));

Be careful to not try to set fields which are not updateable:

Set<String> updateableFields = new Set<String>();
for (SObjectField field : SObjectType.Task.fields.getMap().values())
{
    if (field.getDescribe().isUpdateable())
    {
        updateableFields.add(String.valueOf(field));
    }
}

Generate this list before looping through records individually. Then loop through this field collection instead of the one you are currently using.

| improve this answer | |
  • You should add a comment about filtering out read-only fields to prevent runtime exceptions... – sfdcfox Feb 14 '18 at 22:25
0

In continuation of @Adrain Larson post,
I used below to revert all the changes that user entered except WhoId:

for (Task newTask: Trigger.new) {
   Task oldTask = Trigger.oldMap.get(newTask.ID);
   for(String fieldName : updateableFields){
       if(newTask.get(fieldName) != oldTask.get(fieldName)){
          newTask.put(fieldName, oldTask.get(fieldName));
       }
   }
}
| improve this answer | |

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.