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
Behzad Bahadori 18Behzad Bahadori 18 

Query Community portal User that belongs to an account as a contact

Community portal user belongs to an account in Salesforce as a contact. how do I query the account name of the contact which is a user in the community portal?
Best Answer chosen by Behzad Bahadori 18
Alexander TsitsuraAlexander Tsitsura
// Try to use this controller

public class newOpportunityController {
public User u {get; set;}
public Account account {get; set;}
public Contact contact {get; set;}
public newOpportunityController() {
this.u = [SELECT Id, Contact.AccountId, Contact.Account.Name FROM User WHERE Id = :'00516000006z0O0'];
     System.debug( 'The User Id is' + u);

    this.account =u.Contact.Account;
    this.contact = u.Contact;
}

   public Opportunity getOpportunity() {
      if(opportunity == null) opportunity = new Opportunity();
      return opportunity;
   }

   public OpportunityContactRole getRole() {
      if(role == null) role = new OpportunityContactRole();
      return role;
   }

 public PageReference step1() {
      return Page.newOpptyStep1;
   }
 public PageReference save() {

    
      if(account.Name == null){
        account.Name = 'NoName';
      }    
      account.phone = contact.phone;
      insert account;

    .  
      if(contact.LastName == null){
        contact.LastName = 'NoName';
      }
      if(contact.FirstName == null){
        contact.FirstName = 'NoName';
      }
      contact.accountId = account.id;
      insert contact;
}

Thank,
Alex

All Answers

Alexander TsitsuraAlexander Tsitsura
Hi Behzad,

Try this
ELECT Id, Contact.Account.Name FROM User WHERE isPortalEnabled = true

As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you.

Thanks,
Alex
Behzad Bahadori 18Behzad Bahadori 18
Hi Alexander, Will this give me the parent account of the community user that is currently logged in?
Alexander TsitsuraAlexander Tsitsura
If you need query account for current logged user use query
 
User u = [SELECT Id, Contact.AccountId, Contact.Account.Name FROM User WHERE Id = :UserInfo.getUSerId()];

Thanks,
Alex
Behzad Bahadori 18Behzad Bahadori 18
but does that work for community user ?  so I shouldnt user this SELECT Id, Contact.Account.Name FROM User WHERE isPortalEnabled = true ? I want to get the account name that the current community user belongs to and write it down in a apex page
Alexander TsitsuraAlexander Tsitsura
Yes, this should be work for community User.

UserInfo.getUSerId() - return id of current logged user.

This query returned current logged user
User u = [SELECT Id, Contact.AccountId, Contact.Account.Name FROM User WHERE Id = :UserInfo.getUSerId()];
and you can determine account name using code below
acctName = u.Contact.Account.Name;

And this property you can use on vf page.

Thanks,
Alex
Behzad Bahadori 18Behzad Bahadori 18
Do I need isPortalEnabled = true ?
Behzad Bahadori 18Behzad Bahadori 18
for some reason its showing empty
Alexander TsitsuraAlexander Tsitsura
"isPortalEnabled = true" not required, becouse you used UserInfo.getUserId() for query needed user. Its showing empty if you use not community user. If you logged by community user, you succesfully see account name.
Behzad Bahadori 18Behzad Bahadori 18

This is what I have right now 

controller:  

public class newOpportunityController {
public newOpportunityController() {
User u = [SELECT Id, Contact.AccountId, Contact.Account.Name FROM User WHERE Id = :'00516000006z0O0'];
     System.debug( 'The User Id is' + u);
}
 public Account getAccount() {
      if(account == null) account = new Account();

      return account;
   }



   public Contact getContact() {
      if(contact == null) contact = new Contact();
      return contact;
   }

   public Opportunity getOpportunity() {
      if(opportunity == null) opportunity = new Opportunity();
      return opportunity;
   }

   public OpportunityContactRole getRole() {
      if(role == null) role = new OpportunityContactRole();
      return role;
   }

 public PageReference step1() {
      return Page.newOpptyStep1;
   }
 public PageReference save() {

    
      if(account.Name == null){
        account.Name = 'NoName';
      }    
      account.phone = contact.phone;
      insert account;

    .  
      if(contact.LastName == null){
        contact.LastName = 'NoName';
      }
      if(contact.FirstName == null){
        contact.FirstName = 'NoName';
      }
      contact.accountId = account.id;
      insert contact;
}

APEX Page

<apex:page controller="newOpportunityController"
           tabStyle="Account" sidebar="false" standardStylesheets="false" docType="html-5.0" >

  <apex:form >
    <apex:pageBlock title="Customer Information">

<apex:facet name="footer">
        <apex:commandButton action="{!step2}" value="Next"
                            styleClass="btn"/>
      </apex:facet>
      <apex:pageBlockSection title="Account Information">
       
       <apex:panelGrid columns="2">
       <!-- Account Name -->
        <div >

              <apex:outputLabel value="Account Name " for="accountName"/>
        <apex:inputField id="accountName" value="{!account.name}"/>
        </div>
       
        <!-- Account Type -->

        <!-- USER RIGHT HEREEEE , returns empty -->
        <apex:outputLabel value="Parent Account...." for="ParentAcount"/>
        <apex:outputText value="{!Contact.Account.Name}" id="ParentAcount"  />
        <!-- Till here -->
        <apex:outputLabel value="Account Type" for="accountType"/>
        <apex:inputField value="{!account.Type}" id="accountType"  />
		<!-- Account Phone -->
        <apex:outputLabel value="Phone " for="accountPhone"/>
        <apex:inputField id="accountPhone" value="{!account.Phone}" />

I dont know why it doesnt return the name of the account, am I missing something?
Alexander TsitsuraAlexander Tsitsura
// Try to use this controller

public class newOpportunityController {
public User u {get; set;}
public Account account {get; set;}
public Contact contact {get; set;}
public newOpportunityController() {
this.u = [SELECT Id, Contact.AccountId, Contact.Account.Name FROM User WHERE Id = :'00516000006z0O0'];
     System.debug( 'The User Id is' + u);

    this.account =u.Contact.Account;
    this.contact = u.Contact;
}

   public Opportunity getOpportunity() {
      if(opportunity == null) opportunity = new Opportunity();
      return opportunity;
   }

   public OpportunityContactRole getRole() {
      if(role == null) role = new OpportunityContactRole();
      return role;
   }

 public PageReference step1() {
      return Page.newOpptyStep1;
   }
 public PageReference save() {

    
      if(account.Name == null){
        account.Name = 'NoName';
      }    
      account.phone = contact.phone;
      insert account;

    .  
      if(contact.LastName == null){
        contact.LastName = 'NoName';
      }
      if(contact.FirstName == null){
        contact.FirstName = 'NoName';
      }
      contact.accountId = account.id;
      insert contact;
}

Thank,
Alex
This was selected as the best answer
Behzad Bahadori 18Behzad Bahadori 18
Would this work for <apex:outputLabel value="Parent Account...." for="ParentAcount"/>   <apex:outputText value="{!Contact.Account.Name}" id="ParentAcount"  />  on the Apex page?
Behzad Bahadori 18Behzad Bahadori 18
Do I need 
public Account getAccount() {
      if(account == null) account = new Account();

      return account;
   }

 

   public Contact getContact() {
      if(contact == null) contact = new Contact();
      return contact;
   }
Alexander TsitsuraAlexander Tsitsura
"Would this work for..."
Yeah, this should work

"Do I need..."
No i create public property for account and contact
public Account account {get; set;}
public Contact contact {get; set;}
Thanks,
Alex
 
ManojjenaManojjena
Hi Behzad ,
Basically in portal user ContactId is a field which is related to a contact which is relatted to a account which is a portal /community account .
So if you know the user then you need to get the contactid From the user and then you can get the account .

What exactly your requirment is ,what you want to ? Hard coding any is is not best practice in SFDC .

Thanks
Manoj
Behzad Bahadori 18Behzad Bahadori 18
Alex Thank you so much with your helps , right now Error: when I load the page in the community and i login as a community User, I get  Error occurred while loading a Visualforce page. 
Alexander TsitsuraAlexander Tsitsura
Can u please provide me error message.
Behzad Bahadori 18Behzad Bahadori 18
well the test case is not working now  Class.newOpportunityController.save: line 155, column 1 Class.testnewOpportunityController2.getPortalUser: line 91, column 1 Class.testnewOpportunityController2.newOpportunityController_TestMethod: line 11, column 1
private class testnewOpportunityController2 {
	
	enum PortalType { CSPLiteUser, PowerPartner, PowerCustomerSuccess, CustomerSuccess }

static testmethod void newOpportunityController_TestMethod()   // Name of the test method. Must be the same as the class name 
    {    
    

    	
        User pu = getPortalUser(PortalType.PowerPartner, null, true);
        System.assert([select isPortalEnabled 
                         from user 
                        where id = :pu.id].isPortalEnabled,
                      'User was not flagged as portal enabled.');       
        
        System.RunAs(pu) {
            System.assert([select isPortalEnabled 
                             from user 
                            where id = :UserInfo.getUserId()].isPortalEnabled, 
                          'User wasnt portal enabled within the runas block. ');
        }
    }
    
    public static User getPortalUser(PortalType portalType, User userWithRole, Boolean doInsert) {
    
      
           newOpportunityController s = new newOpportunityController();
        if(userWithRole == null) {   
            
            if(UserInfo.getUserRoleId() == null) {

                UserRole r = new UserRole(name = 'TEST ROLE');
                Database.insert(r);
                
                userWithRole = new User(alias = 'hasrole', email='userwithrole@roletest1.com', userroleid = r.id,
                                    emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
                                    localesidkey='en_US', profileid = UserInfo.getProfileId(), 
                                    timezonesidkey='America/Los_Angeles', username='userwithrole@testorg.com');
            } else {
                userWithRole = new User(Id = UserInfo.getUserId(), UserRoleId = UserInfo.getUserRoleId());
            }
            
            System.assert(userWithRole.userRoleId != null, 
                          'This test requires the target org to have at least one UserRole created. Please create a user role in this organization and try again.');
        }

        Account a;
        Contact c;
        Opportunity opp;
        System.runAs(userWithRole) {

            a = new Account( Name = 'TEST ACCOUNT',Type ='Customer',Phone='3105552266',Fax='2562235544',ShippingStreet = 'Shipping Street',ShippingState = 'Shipping State');
            Database.insert(a);
            
            c = new Contact(AccountId = a.id, FirstName = 'FirstName', LastName = 'lastname', Email = 'choosepros@gmail.com');
            Database.insert(c);

           opp = new Opportunity(name='test Opportunity',stageName='Quote Sent',closedate = system.today(),accountid= a.id);
           Database.insert(opp);
           
           OpportunityContactRole oppconrole = s.getRole();

        }
        
        /* Get any profile for the given type.*/
        Profile p = [select id 
                      from profile 
                     where usertype = :portalType.name() 
                     limit 1];   
        
        String testemail = 'puser000@amamama.com';
        User pu = new User(profileId = p.id, username = testemail, email = testemail, 
                           emailencodingkey = 'UTF-8', localesidkey = 'en_US', 
                           languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles', 
                           alias='cspu', lastname='lastname', contactId = c.id);
        
        if(doInsert) {
            Database.insert(pu);
        }
        
   		 //s.getAccount();                        // Call Function of Original class
       //s.getContact();
       s.getOpportunity();
       //s.getrole();
         s.step1();
         s.step2();
         s.step3();
         
         s.save(); 
         return pu; 
    }
 		 

}
Chetna AgrawalChetna Agrawal
I have written batch class to merge person account, some Accounts portal user are enabled.
I want to disable them first and then we can merge them.
for(Account acc : scope) {
            for(User u : [Select u.Id, u.IsActive, u.IsPortalEnabled from User u where u.AccountId=:acc.id]){
           
              if(u.IsActive || u.IsPortalEnabled ){
                u.IsActive = false;
                u.IsPortalEnabled = false;
           
              }
        }

This code disable the user, but i need to disable person account.