Showing posts with label Custom Controller. Show all posts
Showing posts with label Custom Controller. Show all posts

Monday, July 18, 2016

Salesforce create custom controller

1. Go to "setup/Develop/Apex Classes" and click "new"
2. Write the following code:


public class CustomController {

    public Account account { get; private set; }

    public NewAndExistingController() {
        Id id = ApexPages.currentPage().getParameters().get('id');
        account = (id == null) ? new Account() :
            [SELECT Name, Phone, Industry FROM Account WHERE Id = :id];
    }

    public PageReference save() {
        try {
            upsert(account);
        } 
        catch(System.DMLException e) {
            ApexPages.addMessages(e);
            return null;
        }
        //  After successful Save, navigate to the default view page
        PageReference r = new ApexPages.StandardController(Account).view();
        return (r);
    }
}


3. Go to "setup/Develop/Visualforce Pages" and click "new"
4. Write the following code:

<apex:page controller="CustomController" tabstyle="Account">
    <apex:form>
        <apex:pageBlock mode="edit">
            <apex:pageMessages/>
            <apex:pageBlockSection>
                <apex:inputField value="{!Account.name}"/>
                <apex:inputField value="{!Account.phone}"/>
                <apex:inputField value="{!Account.industry}"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Save" action="{!save}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

5. Go to "setup/Create/Tabs" click on "new" under group "Visualforce Tabs"
6. Select "Visualforce Page" created before & provide other information & save.

7. Browse your custom tab to access the custom tab.