+ Start a Discussion
SFDC8899SFDC8899 

How to deactivate or activate portal users pragmatically

HI,

I need to do activate or deactivate portal community users based on contact record checkbox field.

if the check is ture then that contact can be have access on portal community or else can't become a portal user

kindly share your thoughts nd way of approch 

thanks
Best Answer chosen by SFDC8899
Dilip_VDilip_V
Hi Hemanth,

try this code
 
// 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;
}
Reference:
https://salesforce.stackexchange.com/questions/17389/how-do-i-deactivate-a-portal-user-in-apex-code

Let us know if it works.

Mark it as best answer if it works.

Thanks.
 

All Answers

Dilip_VDilip_V
Hi Hemanth,

try this code
 
// 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;
}
Reference:
https://salesforce.stackexchange.com/questions/17389/how-do-i-deactivate-a-portal-user-in-apex-code

Let us know if it works.

Mark it as best answer if it works.

Thanks.
 
This was selected as the best answer
ARE youARE you
Currently I have some Issues with setting the IsPortalEnabled Checkbox, here is my Code:
User user = [SELECT Id FROM User WHERE Contact.AccountId = :accountId];
// fetch Users Id
 Id uid = user.Id;
user.IsActive = false;
user.IsPortalEnabled = false;
System.debug('IsPortalEnabled before saving: ' + user.IsPortalEnabled);
System.debug('IsActive before saving: ' + user.IsActive);
update user;
// re-fetch User Object
User us = [SELECT Name, IsPortalEnabled, IsActive FROM USER WHERE Id = :user.Id];
System.debug('IsPortalEnabled after saving: ' + us.IsPortalEnabled);
System.debug('IsActive after saving:' + us.IsActive);
Even by setting IsPortalEnabled to false before saving if I re-query the same User Object the Flag will be reset. The change of IsActive is stored as expected.

Here is the console output of my test class:
console output