+ Start a Discussion
sd2008sd2008 

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.

Best Answer chosen by Admin (Salesforce Developers) 
Vijay RautVijay Raut

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

aalbertaalbert

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. 

 

 

sd2008sd2008
thanks
sd2008sd2008

it returns "Illegal Assignment from List:SObject Obj_c to List: Double"

 

trigger GetLastAssocID on Obj__c (before insert) {       List<Double>  tempid = [Select Obj_ID__c from obj__c Order by Obj_ID__c Desc Limit 1];

 

     for (Obj__c ori: System.Trigger.New){

     if (ori.ObjName__c == ''){

         ori.obj__c =tempid(0);

         }

     }

}

 

 

werewolfwerewolf
That error tells you all you need to know.  You're trying to assign the results of a query, which will be a List<Obj_ID__c>, to a List<Double>.  You can't do that.
sd2008sd2008

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

werewolfwerewolf

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

 

 

Vijay RautVijay Raut

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.

This was selected as the best answer
sd2008sd2008
thank you
sd2008sd2008
Thank you