A custom controller is an Apex class that uses the default, no-argument constructor for the outer, top-level class. You cannot create a custom controller constructor that includes parameters.

Building a Custom Controller

The following class is a simple example of a custom 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()
    {
        try
        {
            update account;
        }
        catch (DmlException e)
        {
            ApexPages.addMessages(e);
            return null;
        }
        return new ApexPages.StandardController(account).view();
    }
}

The following Visualforce markup shows how the custom controller above can be used in a 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>
history | excerpt history