0

I am calling an apex class from flow. Inside the apex class, I am trying to activate the user. But I am getting the "Cannot modify a collection while it is being iterated."

Here is my apex code:

public class ActivateUsers
{

@InvocableMethod
public static void ActivateUser(List<user> Users)
{
       list<user> userslist= new list<user>();

       for(user u: Users)

       {
          u.isActive=true;
          userslist.add(u);


       }

       update userslist;

     }
 }

I know what the issue is, just don't know how to resolve it, considering what I am trying to do.

Thanks

Anonymous
  • 3
  • 1
  • 4

2 Answers2

0

I don't believe you can update the input collection of an invocable method. Try passing in a list of IDs instead and re-querying with those IDs as a filter to create a list:

public class ActivateUsers
{

    @InvocableMethod
    public static void ActivateUser(List<Id> UserIds)
    {
       List<User> usersList = [SELECT Id, isActive FROM User WHERE Id in :UserIds];

       for(user u: usersList)

       {
          u.isActive=true;

       }

       update usersList;

     }
 }

You can also then simply update the iterated list after the loop.

ChiefMcFrank
  • 721
  • 4
  • 18
  • Thanks for the help. I tried the above code, I am getting the following error:An Apex error occurred: System.DmlException: Update failed. First exception on row 0 with id 005g0000007Kl0dAAC; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): User, original object: Contact: [] – Anonymous Apr 08 '20 at 22:08
  • I researched on the issue and created another class, copy pasted the code from this class to that class, annotated it with @future keyword And simply called that class from this class. – Anonymous Apr 08 '20 at 22:29
0

The problem is that you are adding to usersList while iterating over usersList. The loop would never finish. The User record you are adding is already in the list. You just need to update the current User record becuase it is a reference to the list element.

public class ActivateUsers
{

@InvocableMethod
public static void ActivateUser(List<user> Users)
{
   list<user> userslist= new list<user>();

   for(user u: Users)

   {
      u.isActive=true;
   }

   update userslist;

 }
 }
TechingCrewMatt
  • 486
  • 2
  • 7