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
bdardinbdardin 

Creating Contact Objects Based on Field Data

On our Project object, we have a Salesman picklist field, which just lists the last name of the salesman who sold the project. We have a Project Contact object on the Project. We want to use this Salesman field to automatically create a Project Contact looking up to the Contact record that corresponds to that salesman. Right now we're currently doing this by hardcoding the IDs of the contacts - which I understand is bad programming, but still works in production. I want to be able to do this without hardcoding the IDs, however I'm floundering over how to query just the salesmen contacts without having a huge OR statement in the where clause for all their last names, and how to then correctly grab the right salesman contact for each project in a for loop. I know I can't use a query inside the for loop. This sounds like something I'd use Maps for - is it possible to construct a Map where the last name as a String is the key and the Contact object (or ID) is the value? Or is there some other way I should do it? I'm an Apex (and programming in general) newbie. Thanks in advance!

Best Answer chosen by Admin (Salesforce Developers) 
Jeff MayJeff May

You can build a Set<String> of the Contact Names you want to search, then SOQL from Contacts where LastName in :yourSet

 

This will give you a List<Contact>.  From there, if you wanted to create a Map<String, Contact>, or Map<String, Id> you can do something like 

 

for (Contact c : myList){

  myMap.put(c.LastName, c.Id);

}

 

 

All Answers

Jeff MayJeff May

You can build a Set<String> of the Contact Names you want to search, then SOQL from Contacts where LastName in :yourSet

 

This will give you a List<Contact>.  From there, if you wanted to create a Map<String, Contact>, or Map<String, Id> you can do something like 

 

for (Contact c : myList){

  myMap.put(c.LastName, c.Id);

}

 

 

This was selected as the best answer
bdardinbdardin

This worked! Thank you so much!