+ Start a Discussion
Chitral ChaddaChitral Chadda 

insert task with fields

trigger populateFields on Task (before insert,before update)
{
 map<id,list<task>> whoids = new map<id,list<task>>();
 for(task t :trigger.new)
 {
 if(t.whoid!=null)
 {
  if(!whoids.containsKey(t.whoid))
  {
  list<task> temp = new list<task>();
  temp.add(t);
  whoids.put(t.whoid,temp);
  }
  else
  {
  whoids.get(t.whoid).add(t);
  }
 } 

}
list<task> tasks = new list<task>();

for(contact c:[select id,Name, MobilePhone,Title from contact where id in:whoids.KeySet()])

{
//for(task t :whoids.get(c.id))
 
 for(task t :trigger.new) {
   t.Mobile__c =c.MobilePhone;
   t.Title__c =c.Title;
  tasks.add(t);
  }
  update tasks;
  
 }  
}



I create a contact
 and then a task , the mobile and title fields are not populated ....in task object ..and there is no error.
Best Answer chosen by Chitral Chadda
nagalakshminagalakshmi
Hi Chitral,

Use this below code. It will work.. let me know if it will not work..

trigger populateFields on Task (before insert,before update)
{
   set<id> whoidset = new set<id>();
   for(task t : trigger.new)
   {
      if(t.whoid != null)
        whoidset.add(t.whoid);
   }
   map<id,contact> contactmap = new map<id,contact>([select id,lastname,MobilePhone,title from contact where id in: whoidset]);
   for(task tt :trigger.new)
   {
       if(tt.whoid != null && contactmap.keyset(tt.whoid))
       {
             tt.Mobile__c = contactmap.get(tt.whoid).MobilePhone;
             tt.Title__c = contactmap.get(tt.whoid).Title;
       }       
   }
}

All Answers

SonamSonam (Salesforce Developers) 
Try and put system.debug lines in the trigger to see if the values are being copied over to:
 t.Mobile__c =c.MobilePhone;
 t.Title__c =c.Title;

start the debug logs for your user and see if the values are coming in these fields..

 
nagalakshminagalakshmi
Hi Chitral,

Use this below code. It will work.. let me know if it will not work..

trigger populateFields on Task (before insert,before update)
{
   set<id> whoidset = new set<id>();
   for(task t : trigger.new)
   {
      if(t.whoid != null)
        whoidset.add(t.whoid);
   }
   map<id,contact> contactmap = new map<id,contact>([select id,lastname,MobilePhone,title from contact where id in: whoidset]);
   for(task tt :trigger.new)
   {
       if(tt.whoid != null && contactmap.keyset(tt.whoid))
       {
             tt.Mobile__c = contactmap.get(tt.whoid).MobilePhone;
             tt.Title__c = contactmap.get(tt.whoid).Title;
       }       
   }
}
This was selected as the best answer
Chitral ChaddaChitral Chadda
@
nagalakshmi

it works
just little change 

if(tt.whoid != null && contactmap.keyset(tt.whoid))
shud be

if(tt.whoid != null && contactmap.containskey(tt.whoid))

thnks 
Chitral ChaddaChitral Chadda
@sonam ty fr help