You need to sign in to do that
Don't have an account?
sd2008
PrePopulate field trigger question
I have a trigger which prepopulate a filed before insert, but it does not work.
trigger GetLastAssocID on Obj__c (before insert) {
for (Obj__c ori: System.Trigger.New){
if (ori.ObjName__c == ''){
ori.Obj_ID__c = [Select Obj_ID__c from
Obj__c
Order by Obj_ID__c Desc
Limit 1];
}
}
}
Obj__c is an object I created and Obj_ID is a number(Double) field.
Hi,
Try following code.
trigger GetLastAssocID on Obj__c (before insert) { Double tempid = [Select Obj_ID__c from obj__c Order by Obj_ID__c Desc Limit 1].Obj_ID__c; for (Obj__c ori: System.Trigger.New) { if (ori.ObjName__c == ''){ ori.obj__c =tempid; } } }
Hope this would help.
Cheers,
V.R.
All Answers
The simplest way to troubleshoot is to add some System.debug messages in the trigger code. Then use the System Logs or Debug Logs to see the output.
Also, you have a query inside the FOR loop which won't scale well. I recommend moving that query outside the for loop, storing the results in a list, map, set, ect, and then referencing that inside the for loop.
it returns "Illegal Assignment from List:SObject Obj_c to List: Double"
for (Obj__c ori: System.Trigger.New){
if (ori.ObjName__c == ''){ori.obj__c =tempid(0);
}}
}
Obj_ID__c is a number field
and I tried several ways it doesn't work
all I want to do is to make sure it gets the selected value
The offending line is:
List<Double> tempid = [Select Obj_ID__c from obj__c Order by Obj_ID__c Desc Limit 1];
It should be:
List<obj__c> tempid = [Select Obj_ID__c from obj__c Order by Obj_ID__c Desc Limit 1];
If you want to get a double out of it, you'll want to make it more like
obj__c tempObj = [Select Obj_ID__c from obj__c Order by Obj_ID__c Desc Limit 1];
double tempid = tempObj.Obj_ID__c
Hi,
Try following code.
trigger GetLastAssocID on Obj__c (before insert) { Double tempid = [Select Obj_ID__c from obj__c Order by Obj_ID__c Desc Limit 1].Obj_ID__c; for (Obj__c ori: System.Trigger.New) { if (ori.ObjName__c == ''){ ori.obj__c =tempid; } } }
Hope this would help.
Cheers,
V.R.