A blog about Salesforce CRM Configuration and development

Saturday, 23 June 2018

Apex Trigger: Update Fields on Case Records when a task is created/updated on Case.



/* Name: TaskDemoTrigger
 * Description: This Trigger will update a field on Case when a task is created or updated.
*/

trigger TaskDemo1Trg on Task (after insert,after update) {
 
    set<id> parentId=new set<id>();
    if(Trigger.isInsert || Trigger.isUpdate){
        for(Task t:trigger.new){
            if(t.whatid.getSobjectType()==Case.sObjectType){
                parentId.add(t.whatId);
            }
        }
    }
    system.debug('Parent id is: ' +parentId);
    Map<id,Case> caseMap=new Map<id,Case>([select id,Tasks_Created_Date__c from Case where id IN: parentId]);
    list<Case> caseList=new List<Case>();
 
    for(Task t:Trigger.new){
        if(t.WhatId.getSObjectType()==Case.sObjectType){
            if(caseMap.containsKey(t.WhatId)){
                Case c=caseMap.get(t.WhatId);
                if(c!=null){
                    c.Tasks_Created_Date__c=t.Subject +' : '+ string.valueOf(t.CreatedDate);
                }
            }
        }
        if(!caseMap.isEmpty()){
            update caseMap.values();
        }
    }
}
Share:

2 comments:

Trailhead Profile


Follow by Email

Total Pageviews

Followers

Popular Posts

Powered by Blogger.

Contact form

Name

Email *

Message *