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
Saad Ahmad 27Saad Ahmad 27 

Using APEX instead of Visual Flow

I have created a Visual Flow to update look up fields based on the User ID field. E.g.
User ID field = 1234. The Visual Flow looks up all the User records from the User object and assigns the name of User ID 1234 to the User Name field on the record.
Due to the number of User ID fields that have to be looked up, the Flow is hitting governer limits. I'd like to create a batchable Apex to achieve this and I was wondering if this would be possible? I'd appreciate any help/guidance on this!

User-added image

 
Best Answer chosen by Saad Ahmad 27
ArleneArlene
I'm sure I'm misunderstanding what you want to do.  It sounds like you want to update every single User record to have the same name?

You will only probably need to use Batch Apex if you are updating a large number of records.  Otherwise, you can bulkify your code without using batch Apex.  In either case, the general pattern is the same:

1.  Loop through the records you intend to update, gathering the user Ids from all of them, building a Set of Ids as you go.
2. Use a single SELECT statement to select all the User records you will need to lookup values in, by using the IN clause of the select statement and the set you built in the step above.  Return a Map (not a List) from the SELECT statement to make the next step easier.
3.  Loop through your original records again, using the key to the Map to find the values for the appropriate User record in the Map.  As you loop, you update the records you are looping through.
4.  Finally, use a single update statement to update all the records you updated in the step above.

That's rather generic, but I hope it points you in the right direction.  This solution only has 2 select statements (the original records to be updated, and the User records to be used for lookups) and 1 update statement (to update the original records now modified).  This will be your solution if the governor limits you are hitting are related to the number of statements.  

If the governor limits you are hitting are instead related to the number rows, you may need to do Batch Apex.  It uses the same pattern above, but runs the same 4 steps repeatedly for smaller batches of records.