+ Start a Discussion
sd2008sd2008 

A Trigger PrePopulate field 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) 
jpizzalajpizzala

A few things:

  • "System.Trigger.New" should be changed to "Trigger.new"
  • Is your ObjName__c field truly a custom field or are you trying to get at the default name field?  If the latter, use "ori.name"
  • You should check to see if ori.ObjName__c is null before checking for an empty string, also use the equals() method for string comparisons
    • if( ori.ObjName__c == null || ori.ObjName__c.equals( '' ) ) { ... }

       

  • By putting a SOQL statement (your "select" query) inside of a FOR loop, you are begging the governors to reject your trigger's execution
  • Your SOQL statement is going to return a Obj__c record, not just an id.  Normally, SOQL queries will return a List of records.  However, since you specify "limit 1", a single Obj__c record will be returned and you will not have to iterate over a List.
  • This is more of an Apex question, not a Force.com Sites question, please post similar questions on the "Apex Code Development" board.

Hope this helps!

All Answers

jpizzalajpizzala

A few things:

  • "System.Trigger.New" should be changed to "Trigger.new"
  • Is your ObjName__c field truly a custom field or are you trying to get at the default name field?  If the latter, use "ori.name"
  • You should check to see if ori.ObjName__c is null before checking for an empty string, also use the equals() method for string comparisons
    • if( ori.ObjName__c == null || ori.ObjName__c.equals( '' ) ) { ... }

       

  • By putting a SOQL statement (your "select" query) inside of a FOR loop, you are begging the governors to reject your trigger's execution
  • Your SOQL statement is going to return a Obj__c record, not just an id.  Normally, SOQL queries will return a List of records.  However, since you specify "limit 1", a single Obj__c record will be returned and you will not have to iterate over a List.
  • This is more of an Apex question, not a Force.com Sites question, please post similar questions on the "Apex Code Development" board.

Hope this helps!
This was selected as the best answer
sd2008sd2008
thanks