+ Start a Discussion
BylithiumBylithium 

Trigger on Task

I am trying to write a Trigger on Task which has Member_Number__c field, whenever I create a task and select related account I want the Member_Number__c field to be populated with the respective Account_Number__c from Account Object.

 

I am having problems with the mapping as I am not able to figure out how to map Task and Account Fields.

 

trigger Memberidupdate on Task (before insert) {

id accid = Trigger.new[0].AccountId;
Map<id,String> taskaccmap = new Map<id,String>();
String accfield,Taskfield;

Task [] newTask;
newTask = [select id,AccountId,Member_Number__c from Task where id=:accid];
Taskfield = newTask[0].Account_Number__c;


Account [] Acc;
acc = [select id,Account_Number__c from Account where id=:accid];
accfield = acc[0].Account_Number__c;


taskaccmap.put(Taskfield,accfield);


}

Best Answer chosen by Admin (Salesforce Developers) 
BylithiumBylithium

Thanks a lot..It worked

I used whatid instead of Accountid

All Answers

Alok_NagarroAlok_Nagarro

Hi,

 

You r trying to fetch record which has not created actually (because trigger is fired on before insert).

The marked code is creating problem.

 

trigger Memberidupdate on Task (before insert) {

id accid = Trigger.new[0].AccountId;
Map<id,String> taskaccmap = new Map<id,String>();
String accfield,Taskfield;

Task [] newTask;
newTask = [select id,AccountId,Member_Number__c fr om Task where id=:accid];
Taskfield = newTask[0].Account_Number__c;


Account [] Acc;
acc = [select id,Account_Number__c from Account where id=:accid];
accfield = acc[0].Account_Number__c;


taskaccmap.put(Taskfield,accfield);


}

BylithiumBylithium

If I change it to after insert I still have issues...Can you help me to correct the code. 

Pradeep_NavatarPradeep_Navatar

Please find below the sample trigger :

 

trigger Memberidupdate on Task (before insert) {

      if(Trigger.isBefore)

      {

            for(Task tsk:Trigger.new)

            {

                  if(tsk.AccountId ! = null || tsk.AccountId ! = '')

                  {

                        String strTemp=[select Account_Number__c from Account where id = :tsk.AccountId].Account_Number__c;

                        tsk.Member_Number__c = strTemp;

                  }

            }

      }

}

 

Hope this helps.

BylithiumBylithium

Thanks a lot..It worked

I used whatid instead of Accountid

This was selected as the best answer
JAW99JAW99

Hello, am trying to something similar, to update a custom date field with the date of the inserted task, but am getting

Error: Compile Error: Illegal assignment from Datetime to String at line

Can you assist thanks?!