function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Faizan Ali 17Faizan Ali 17 

Lookup autofill with a selected picklist value?

Hi all,

I have a picklist that has names (text) that are the same as my contact names (Appointment_with__c)

I have a lookup field to contact that I want to autofill whenever a name is selected from my picklist. The lookup field is called (Staff__c)

I made a basic trigger but encountering silly errors and perhaps not the best code as I am a beginner:

trigger Autofill on Event (before insert, before update) {
    
    Set<String> ids = new Set<String>();
    
    for(Event evt: Trigger.New)
    {
        if(evt.Appointment_with__c != null)
        {
            ids.add(evt.Appointment_with__c);
        }
    }
    
    List<Staff__c> dclocation = [SELECT Id, Name FROM Staff__c WHERE Name in: ids];
    
    for(Event evt1: Trigger.New)
    {
        evt1.Staff__c = dclocation[0].id;
    }
}

I keep getting 'Invalid type: Staff__c'
Variable does not exist: id'
Best Answer chosen by Faizan Ali 17
RituSharmaRituSharma
Is seems that Staff__c is not the exact API name of the object. Check the name in your org and update in the code.

All Answers

Faizan Ali 17Faizan Ali 17
Appointment_with__c is my picklist field
Staff__c is my lookup field

This is in my Event object.
RituSharmaRituSharma
Try below code:
trigger Autofill on Event (before insert, before update) {
    
    Set<String> ids = new Set<String>();
    
    for(Event evt: Trigger.New)
    {
        if(evt.Appointment_with__c != null)
        {
            ids.add(evt.Appointment_with__c);
        }
    }
        
    //Query records and loop on them to prepare a map where key is the name
    Map<String,Staff__c> dclocationMap = new Map<String,Staff__c>();
    for(Staff__c rec: [SELECT Id, Name FROM Staff__c WHERE Name in: ids]) {
        dclocationMap.put(rec.Name, rec);
    }
    
    for(Event evt1: Trigger.New)
    {
        evt1.Staff__c = dclocationMap.get(evt1.Appointment_with__c).Id;
    }
}
Faizan Ali 17Faizan Ali 17
User-added image

Unfortunately getting more errors :(
RituSharmaRituSharma
Is seems that Staff__c is not the exact API name of the object. Check the name in your org and update in the code.
This was selected as the best answer