You need to sign in to do that
Don't have an account?
Nong
How to get Account information from Task trigger?
Dear All,
Could you please help me to give some example APEX code to get value of Account custom field from Task trigger.
As i would like to set default value on Task custom field depending on selected Rating of Account object that this task is under.
Thank you very much in advance for your help.
Best Regards
Anong
Dear All,
I have found the solution from other topic so i put the source code here for other people reference in the future.
=================================================================
trigger AccountRating_TaskBudget on Task (before insert) {
String strRating ='';
Integer iBudget =0;
Task tsk=Trigger.new[0];
if(tsk.whatid!= null || tsk.whatid!= '')
{
strRating=[select Rating from Account where id = :tsk.whatid].Rating ;
strRating=strRating.toUpperCase();
//set budget via Account rating
if (strRating == 'A1') {
iBudget =500;
} else if (strRating == 'A2') {
iBudget =500;
} else if (strRating == 'A3') {
iBudget =200;
} else if (strRating == 'A4') {
iBudget =200;
} else if (strRating == 'A5') {
iBudget =100;
} else {
iBudget = 0;
}
tsk.Budget__c = iBudget;
}//if
}
====================================================================
Regards
Anong
Hi, I think there is a problem in your if statement. You should be using && not ||.
if(tsk.whatid!= null && tsk.whatid!= '') --> If tsk.whatid does not equal null AND does not equal the empty string
it is theoretically possible for the whatid to be equal to null but not the empty string and vice-versa.
You can also consolidate your code a little more and bulkify it.
Hello kyle.t ,
Thank you very much for your suggestion.
After i tried with your suggestion i got the error ' Invalid foreign key relationship: Task.Account__r at' , could you please help.
Best Regards
Anong
Below is the sample code to update the Account_Rating__C custom field in Task from the Rating__c custom field of selected Account :
trigger TaskPopulateRating on Task (before insert)
{
list<Account> acc;
Task T = Trigger.New[0];
String str = T.whoId;
if(str != null)
{
str = str.substring(0,3);
}
if(str == '001')
{
acc = [select Rating__c From Account where id=:T.whoId];
T.Account_Rating__C = acc.Rating__c;
}
}
Sorry about that, forgot you can use the dot notation with Tasks. I created this in a dev environment that I have and it should work for you. You need to gather up all of the accounts before you enter the for loop and make a map out of them. once you have that, you can apply your logic.