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
Phuc Nguyen 18Phuc Nguyen 18 

Apex class search for value in Field

On creation of a record I need to update its name based on a value on existing records.
For example a new record is created and the code Id is 12345
If a record exist with this value I need to set the new record code Id to 12345_001.  This will continue so if the latestcode ID value is 12345_054 the new code Id needs to be 12345_055
So how do I search for this value and set the new one?   Will this be an issue on data loads?
Thanks,
P​​​​​​​  
Best Answer chosen by Phuc Nguyen 18
RituSharmaRituSharma
Since you need to write bulkified code, loop on new records(trigger.new) and store the list of code ids in a set. Then you may use the set to query the records. Then you may use aggregate results to get the count against each code id.

Refer the URL to see how you can use aggregate results -> https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_agg_functions.htm

All Answers

RituSharmaRituSharma
You may achieve this either using trigger or lightning flow. Based on code, query the existing records and then get the number after _ and then append 1 to it and use this value for the new record. It will cuase issues if you are inserting bulk records. To avoid the issues during data load, put the record code in your load file itself and map that while loading data. In your logic, use a flag(based on setting/metadase) and if the flag is true then bypass the logic that you will write for setting the code.
Phuc Nguyen 18Phuc Nguyen 18
Thank you for the reply.  That is where I am having an issue.  How do I get the count of existing records with the same postal code?  Not sure what that mapping looks like.
RituSharmaRituSharma
Since you need to write bulkified code, loop on new records(trigger.new) and store the list of code ids in a set. Then you may use the set to query the records. Then you may use aggregate results to get the count against each code id.

Refer the URL to see how you can use aggregate results -> https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_agg_functions.htm
This was selected as the best answer