Search code examples
triggerssalesforcevisualforce

How to set a Lookup Field via a Salesforce Trigger


I want to set a Lookup Field using a salesforce apex trigger, but I keep getting an error:

System.StringException: Invalid id:

I have a custom object called Job__c. It has a custom pick list for accounts: Acct__c.

A user will populate Acct__c as John Deer, the trigger should add John Deer to the Account__c lookup field.

Here is the trigger:

trigger UpdateAccounts on Job__c (before insert) {
    for (Job__c obj: trigger.new){
        obj.Account__c = obj.Acct__c;           //Exception is thrown here
}

Exception thrown:

System.StringException: Invalid id:

I tried something different:

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);
        }    
    }
}

That code throws:

Error:Apex trigger UpdateAccounts caused an unexpected exception, contact your 
administrator: UpdateAccounts: execution of BeforeUpdate caused by: 
System.StringException: Invalid id: 

What am I doing wrong that it tells me it's an invalid ID?


Solution

  • Account__c is a look-up field, you cannot assign a string (the picklist field) to it. Instead you have to assign it an account id.

    I am not sure why you're using the account names in the picklist field, but if you want to continue doing that then there's a simple solution that the account names are unique.

    Get the id for the account selected in the query for the id, something like this:

    list<account> acclist = [select id from account where name In yourNameList];
    

    And then in the trigger reference the id

    obj.account__c = accList[0].id;
    

    Make use of maps , do not add the soql's inside for loop