+ Start a Discussion
David PoynterDavid Poynter 

How can you change/update fields for all accounts/contacts in a company?

Hello Apex Developers!

I am a new employee at a wealth management first. Due to the type of industry wealth management is, fields ar changing and being updated quite often (lets say as an example, tax brackets in a drop down list). I have been blazing my way through TrialHead, and have REALLY been enjoying what I have found, and my mind is loving all the opportunites I now have to create solutions for the firm, especially in regards to work flows and APEX. Anyways, back to it...

So lets say tax brackets change, or a field is replaced with another. The firm in history has created a new field, run reports, and used data loader to update fields. However none of them ever new anything about Apex, and after going through trailhead, I can't help but see the simplicity and power of it. I am familiar with coding laguages, and know there must be a simple way to iterate through all accounts or contacts looking for a certain field and entry, and updating it and assinging it to the new updated field options. Yet is seems like this actually may not be that simple using apex. Am I supposed to use a batch function, or is there a way I can run loops?

I don't need the code handed to me on a platter, but I would really appreciate a solution framework as to how I could use apex to update these fields relatively easily. If "I" could find a solution as to how I could do this, it would be implemented a couple times a week, and save countless hours of hassle and frustration.

Thank you so much guys, let me know what you think!

- David

UC InnovationUC Innovation
Hi David,

I am glad you took the time to try and learn Apex via Trailhead modules. They are really informative and engaging and definately show results if you are consistent and involved in them. Anyway, it sounds like you need help mass updating records. The simplest way to accomplish this is using batch apex which is a pretty simple topic. Look here (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm) for more information on the subject.

To summarize, this class type requires three meathods to exist inside of it in order to accomplish the given task. start(), execute(), and finish() with an optional overloaded constructor which I use when I write batch apex. Start() queries all of the records that will be processed. These records are then broken up into batches and processed individually. The size of these can be specified but must be under 200 inclusively (SF limit). You can controll what records will be processed in the query bit but in yor case it seems like you will be processing ALL accounts so you can simply do the following query.
 
SELECT Id
FROM Account

The execute() method is where these records will be processed and you can place any logic concerning updating fields there while considering the amount of records being processed and salesfoce governor limits (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm). If doing one record per batch or 200 and anything in between.

The finish() method is responsable for smaller tasks such as sending emails when batch completes or kicking off any additional batches.

I hope this summary helps!
Feel free to ask any additional questions on this or any other topic.

AM
Rafael Suarez 13Rafael Suarez 13
Hey David, welcome to Apex.

The easiest way is using this thing called "Execute Anonymous" on the Developer Console.
The console link is available at the oval dropdown that shows your name (Top Right) 

Or: https://{orgLocation}.salesforce.com/_ui/common/apex/debug/ApexCSIPage​ and  CTRL-E  {Open Exec Anonymous}

There's lots of posts around on how to to Insert, update or even delete from your object using Apex. Careful though. No Undo's here.

Have fun!

Rafa
 
Alain CabonAlain Cabon
Hi David,

dataloader is an excellent tool for mass updates in bulk mode (free tool) but it can be scheduled only under windows. The Data Loader command-line interface is supported for Windows only.  https://developer.salesforce.com/docs/atlas.en-us.dataLoader.meta/dataLoader/using_the_command_line_interface.htm

The main problem is : do you need a scheduled batch process using flat files received daily or monthly for example?

You can solve the problem easily with dataloader but with Apex, you need to upload the flat files ... manually (not acceptable for a daily process).

With Apex, mass updates can be done using the following pattern given by Salesforce but Apex is not an ETL.
global class SearchAndReplace implements Database.Batchable<sObject>{

   global final String Query;
   global final String Entity;
   global final String Field;
   global final String Value;

   global SearchAndReplace(String q, String e, String f, String v){
      Query=q; Entity=e; Field=f;Value=v;
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<sObject> scope){
     for(sobject s : scope){
        s.put(Field,Value); 
     }
     update scope;
    }

   global void finish(Database.BatchableContext BC){
   }
}
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm

Using the query locator, you can update all your accounts and contacts easily (limit 50,000,000 rows, large margin, extra large).
The global batch process can last for hours because it works automatically by limited scopes.

https://developer.financialforce.com/customizations/importing-large-csv-files-via-batch-apex/

But like for the famous ads, "where is the beef?", it is "where is the file?" and finally, dataloader is still the (only) good free solution.

Best regards

Alain
Rafael Suarez 14Rafael Suarez 14
Hey @Alain regarding your statement "dataloader is an excellent tool for mass updates in bulk mode (free tool) but it can be scheduled only under windows. The Data Loader command-line interface is supported for Windows only."

Be aware thats somewhat misleading.  Though thats SFDC official word,  the CLIq will work under certain Linux distros.  I recently pulled it off within AWS AMI.

Just my 2 cts. 
Rafa
David PoynterDavid Poynter
I am a newbie, so I don't know lots of the terms used. But from what I know I was asking and looking for, the first response, by UC Innovation, is definately the closest answer I was looking for. It's definately not a schedule update... Here's kinda what I am looking for, if I were to write it in a code more similar to C++,

"Create a loop that itterates through all objects of a given type in my org (either a contact or an account/household)
Look for a certain field in the given object.
If the field contains a certain value, assign a certain value to the new field (this field will have been created outside apex ahead of time)."

After that, I could run a couple slight variations of the code, or with just more field changes, so that afterward I could simply delete the old outdated field.
That is all I am really looking to do.

So right now, in my Developer org, I created a new field in contact called "Test1__c". This is a number field.
I then created another field in a contact, called "Test2__c", which is a picklist value field, with a rage of numbers.

I want to create a code, that looks through all my contacts, and if there is a contact with the value 16 in "Test1__c", then it assigns the correlating "16" value from the picklist, in field "Test2__c".

Using laymans terms, and only using apex, can I do this? (We know how to use dataloader, and although yes we could use it to do this... I would really rather use Apex, enter some data in the code, run it, and be done.)
I then hope to be able to keep creating code like this, write explenations of how to use it, and leave it so that anyone in the Techonology team can easily change and update fields, without having to spend hours creating reports, assinging relationships, and importing the reports through dataloader.
Does this all make any sense?? Is it possible?