Is it possible to deactivate a Customer Portal user using Apex?
2 Answers
// Assume cIds is a list of Contacts whose users we wish to deactivate
List<User> usersToUpdate = new List<User>();
for(User u : [Select u.Id, u.IsActive, u.IsPortalEnabled from User u where u.ContactId in :cIds]){
if(u.IsActive || u.IsPortalEnabled ){
u.IsActive = false;
u.IsPortalEnabled = false;
usersToUpdate.add(u);
}
}
if (usersToUpdate.size()>0){
update usersToUpdate;
}
The above snippet might help.
-
i got the error testing through postman.."Update failed. First exception on row 0 with id 00590000001g7hXAAQ; first error: FIELD_INTEGRITY_EXCEPTION, Cannot de-activate self: Active: [IsActive]" Commented Sep 27, 2013 at 13:45
-
Try deactivating a user other than the one you're logged in as! I just verified that Mohith's code works just fine. Commented Sep 27, 2013 at 16:35
-
Thanks @metadaddy for veryfying .Had no time to respond :-( Commented Sep 27, 2013 at 17:15
-
If that answers your question then please mark as answered . Commented Sep 30, 2013 at 6:45
-
Isn't setting IsPortalEnabled to false enough? Or should it always be accompanied with IsActive = false; as well? Commented Dec 11, 2018 at 13:54
This question was asked and last answered back in 2013. In 2021, it seems that attempting to update User.isActive in the same update operation that sets User.isPortalEnabled will actually cause the update operation to fail.
When you set User.isPortalEnabled = false SFDC will automatically set User.isActive to false and User.ContactId to null, which is what we want.
So, for a collection of Contact ID's named "contactIds" that are related to User records you would like to disable:
List<User> usersToDisable = [select id from User where ContactId in :contactIds];
for (User u : usersToDisable) {
u.isPortalEnabled = false;
}
update usersToDisable;