[SalesForce] Pass Contact’s Account Id from VF page to controller

I'm trying to follow this simple example.

Controller

public class MyController {

    private final Account account;

    public MyController() {
        account = [SELECT Id, Name, Site FROM Account 
                   WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    }

    public Account getAccount() {
        return account;
    }

    public PageReference save() {
        update account;
        return null;
    }
}

VF Page:

<apex:page controller="myController" tabStyle="Account">
    <apex:form>
        <apex:pageBlock title="Congratulations {!$User.FirstName}">
            You belong to Account Name: <apex:inputField value="{!account.name}"/>
            <apex:commandButton action="{!save}" value="save"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>

I would like to pass the Contact's Account Id to the controller (I'm referring to a community user), If I do it manually (i.e. typing the AccountID in the URL) it works.

I tried this line of code:

<apex:param name="Id" value="{!$Contact.Accountid}"/> 

But I get an error that the field does not exist, what am I missing?

Best Answer

You don't need to use page parameters at all for this information. You can query for it directly:

User runningUser = [SELECT Contact.AccountId FROM User WHERE Id = :UserInfo.getUserId()];
Account runningUserAccount = [
    SELECT Name, Site FROM Account
    WHERE Id = :runningUser.Contact.AccountId
];
Related Topic