-1

My requirement is once any user creates a new task, and the Related to value is "sales", the field Campaign will be updated automatically with the value from Related To field.

The data type of both Campaign and Related to are lookup.how would I accomplish this?

enter image description here

2
  • Hi there! Can you clarify your question a bit? Your question is about updating one lookup on a task record with the value from another lookup on that same record when it is created, but your sample code doesn't reference the task object, and instead references two custom objects, inserting one of them. What are you trying to accomplish and what is the context?
    – Jeff Kranz
    May 13, 2022 at 12:48
  • on creating a new task, populate a field automatically with the value from another lookup field is the context. ignore the code if it is wrong please give me an idea on how to accomplish this?@JeffKranz May 13, 2022 at 12:58

1 Answer 1

0

Since the Related to (What) field on the Task object is a polymorphic field, first you need to check what kind of record the task record has been created for. and then you can assign the Campaign field on a before trigger based on your requirements, just like this:

trigger TaskTrigger on Task (before insert) {
    
    for (Task t : Trigger.new) {
        // replace 'Sales' with your Object API Name
        if (t.WhatId.getSobjectType().getDescribe().getName() == 'Sales') {
            // update below field with your Campaign API Field name
            t.Campaign__c = t.WhatId;
        }
    }
}

useful links to look at:

Hope this helps with your question.

1
  • N.B. 1) t.WhatId might be NULL as not all Tasks require a Whatid; and (2) more concise is t.WhatId?.getSobjectType() == Sales__c.SobjectType
    – cropredy
    May 19, 2022 at 1:18

You must log in to answer this question.

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