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
Vaibhav SuleVaibhav Sule 

Updating field for a list of custom objects

Hello,
Is it possible in Apex to update a particular field in a custom object for a list of those objects at the same time?

Here's what I am trying to do:
I have a custom object 'myCustomObj', which has a custom field 'myCustomField'.
I have a list of these objects created  already. I want to update the 'myCustomField' for all these objects.

Here's a snippet of my code, which is creating the list of objects correctly, but the update function doesn't seem to work.

 myCustomObj[] myList = new List<myCustomObj>();
 myList = [Select Name, ID, myCustomField from myCustomObj]; //this list gets created as expected
       integer max = mylist.size();
       for (integer i = 0; i< max; i++){
           Decimal x = myList[i].myCustomField; //I am able to read the value in this custom field correctly for all objects in the list 
           myList[i].myCustomField = x + 1;
           update myList[i];
       }
       update myList;//this seems to just update the list. How do I actually update the custom object?

Thanks in advance



 
Best Answer chosen by Vaibhav Sule
Amit Chaudhary 8Amit Chaudhary 8
Please try to use below code.

        List<myCustomObj> myList = new List<myCustomObj>();
        myList = [Select Name, ID, myCustomField from myCustomObj]; //this list gets created as expected

        for(myCustomObj obj : myList )
        {
            obj.myCustomField = obj.myCustomField + 1;
        }
        if(myList.size() > 0)
        {
            update myList;//this seems to just update the list. How do I actually update the custom object?
        }

NOTE:- Never use DML inside the for loop.

Please let us know if this will help you

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please try to use below code.

        List<myCustomObj> myList = new List<myCustomObj>();
        myList = [Select Name, ID, myCustomField from myCustomObj]; //this list gets created as expected

        for(myCustomObj obj : myList )
        {
            obj.myCustomField = obj.myCustomField + 1;
        }
        if(myList.size() > 0)
        {
            update myList;//this seems to just update the list. How do I actually update the custom object?
        }

NOTE:- Never use DML inside the for loop.

Please let us know if this will help you
This was selected as the best answer
Vaibhav SuleVaibhav Sule
Thanks a lot for the quick reply. This helps, the code you suggested works.