3

Is it possible to deactivate a Customer Portal user using Apex?

8
// 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.

8
  • 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]" Sep 27 '13 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.
    – metadaddy
    Sep 27 '13 at 16:35
  • Thanks @metadaddy for veryfying .Had no time to respond :-( Sep 27 '13 at 17:15
  • If that answers your question then please mark as answered . Sep 30 '13 at 6:45
  • Isn't setting IsPortalEnabled to false enough? Or should it always be accompanied with IsActive = false; as well? Dec 11 '18 at 13:54
3

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.