function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dan AskewDan Askew 

Auto-Assign task to object owner

I am attempting to make it so that the user assigning a task isn't the one that is defaulted as the "assign to" and instead the "Assign to" is the owner of the object that the task is referencing.

For instance:
John is owned by Jane. If I assign a task on John's object, I'd like it to default to Jane instead of me.

How can I assign this in setup?
AnkaiahAnkaiah (Salesforce Developers) 
Hi Dan,

for which object you need to update the assigned to as record owner?

Thanks!!
Dan AskewDan Askew
I believe it's Contact, which we have renamed to Student.
AnkaiahAnkaiah (Salesforce Developers) 
Hi Dan,

try with below code.
trigger updateAssignto on Contact(before insert,before update){

set<id> contactids = new set<id>();

for(task t:trigger.new){
if(t.WhoID !=Null && t.WhoId.getSObjectType() == Contact.sObjectType){
contactids.add(t.WhoID);
}
}

map<id,string> contactwithownerids = new map<id,string>();

for(contact con:[select id,ownerid from contact where id iN:contactids]){
contactwithownerids.put(con.id,con.ownerid);
}

for(task t:trigger.new){
if(contactwithownerids.containskey(t.whoId)){
t.ownerId = contactwithownerids.get(t.whoId);
}
}
}

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​