+ Start a Discussion
DoctorCodeDoctorCode 

update a lookup field

i have a lookup field to contacts in the lead and i want a field up the lookup field base in the name the user select in a pick list, the picklist have the names of some of the contact i have 

for example in the picklist i have kevin johnson if the user select kevin i want the triger to prepopulate the lookup field so the lead relates to that contact

 

is this possible 

 

i was playing with the trigger and this is what i got

 

 

trigger updateAE on Lead (after insert) {
  for (lead l:Trigger.new){
  l.L_RRx_AE__c = l.L_Special_Instructions__c;
    }
  }

 and every time i used it a get and error saying :

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger updateAE caused an unexpected exception, contact your administrator: updateAE: execution of AfterInsert caused by: System.StringException: Invalid id: kevin johnson: Trigger.updateAE: line 3, column 3

 

 

Best Answer chosen by Admin (Salesforce Developers) 
WizradWizrad

Lookups expect Salesforce Ids.

 

Youll want to do something like the following

 

 

trigger updateAE on Lead (after insert) {
  List<String> nameList = new List<String>();
  for (lead l:Trigger.new){
    nameList.add(l.L_Special_Instructions__c);
  }

  List<Contact> contactList = [SELECT Id, Name FROM Contact WHERE Name in :nameList];

  Map<String, Id> nameToId = new Map<String, Id>();
  for(Contact c : contactList) {
    nameToId.put(c.Name, c.Id);
  }

  for (lead l:Trigger.new){
  l.L_RRx_AE__c = nameToId.get(l.L_Special_Instructions__c);
  }
}

 

You should also make this a before insert trigger.

 

All Answers

WizradWizrad

Lookups expect Salesforce Ids.

 

Youll want to do something like the following

 

 

trigger updateAE on Lead (after insert) {
  List<String> nameList = new List<String>();
  for (lead l:Trigger.new){
    nameList.add(l.L_Special_Instructions__c);
  }

  List<Contact> contactList = [SELECT Id, Name FROM Contact WHERE Name in :nameList];

  Map<String, Id> nameToId = new Map<String, Id>();
  for(Contact c : contactList) {
    nameToId.put(c.Name, c.Id);
  }

  for (lead l:Trigger.new){
  l.L_RRx_AE__c = nameToId.get(l.L_Special_Instructions__c);
  }
}

 

You should also make this a before insert trigger.

 

This was selected as the best answer
DoctorCodeDoctorCode

**bleep** man that was awesome thanks for the help so now I just need to figure the test right? I mean in order to make it to the production