1

I'm trying nothing more than to update a lookup field when I create a new record. The field it should pull the value from is a lookup.

I have this code:

List <Job__c> opListInsert = new List<Job__c>();
  List <Job__c> opListUpdate = new List<Job__c>();
   if(trigger.isInsert){
    for(Job__c op:trigger.New){
    if(op.Acct__c != Null){
        op.Account__c = op.Acct__c;
        opListInsert.add(op); }
     }
    }  
  else if(trigger.isUpdate){
    for(Job__c op:trigger.New){
     if(op.Acct__c != Null && op.Acct__c !=trigger.oldMap.get(op.id).Acct__c){
         op.Account__c = op.Acct__c;
          opListUpdate.add(op);
    }    
 }

}

But it's throwing the following error:

Error:Apex trigger UpdateAccounts caused an unexpected exception, contact your administrator: UpdateAccounts: execution of BeforeUpdate caused by: System.StringException: Invalid id: accountname : Trigger.UpdateAccounts: line 20, column 1

Anyone know how I can convert the account to string or vice versa?

Update

Thanks for the help, don't know why I figured it would add the string not the ID.

Here is my updated trigger that works (might not be the cleanest option):

trigger UpdateAcct on Job__c (before insert, before update) {

List<String> Accounts = new List<String>(); 
for (Job__c obj: trigger.new){
   Accounts.add(obj.Acct__c);
}
list<Account> acctlist = [select Name from account where Name in :Accounts];
  if (acctlist.size() > 0 ){
    for (Integer i = 0; i < Trigger.new.size(); i++){
      if (Trigger.new[i].Acct__c != null){
        Trigger.new[i].Account__c = acctlist[i].ID; 
      }   
      else{
        Trigger.new[i].Account__c = null;
      }
    }
  }
}
2
  • 3
    Are you sure Job__c.Acct__c is a lookup field? If it is it should contain a valid Id or null. – Daniel Ballinger May 22 '13 at 23:20
  • 1
    Acct__c s a lookup field. Account__c is a picklist. – gato negro May 23 '13 at 15:42
3

Id to String conversion (and the reverse) is handled automatically when you do an assignment. If you get an invalid ID error it means that the String value is not a valid 15 or 18 character Salesforce identifier.

What are the values in the picklists? If they're account names then you can't assign the name to a lookup field. If the picklist is a list of IDs it should work ok in code (in formulae you need to call the TEXT() funciton).

I suspect you're either not using IDs in the picklist, or an ID is not being selected, in which case you need to assign null, or do no assignment, rather than assigning an empty string.

1
  • The picklist values are account names. The logic is to update the lookup using the picklist, so the IDs must be null. Any suggestion on how the trigger might look incorporating the null value? – gato negro May 23 '13 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.