actionfunction visualforce salesforce

actionfunction visualforce salesforce

actionfunction component provides support for invoking controller action methods directly from JavaScript code using an AJAX request.

It is different from actionsupport which only provides support for invoking controller action methods from other Visualforce components, actionfunction defines a new JavaScript function which can then be called from JavaScript code.

Click for Demo

In the example below, we are showing one picklist with name customer priority. Whenever we will change customer , then javascript method will be called. And we have specified corresponding controller action method in actionfunction component method. In controller method we are checking if customer priority is high then we are setting boolean variable as true. So phone textbox will be rendered automatically without refreshing full page

Visualforce Code:

<apex:page controller="actionFunctionController" tabStyle="Account">
    <apex:form >
        <apex:actionFunction name="priorityChangedJavaScript" action="{!priorityChanged}" rerender="out"/>
        <apex:pageBlock >
            <apex:pageBlockSection title="If you will select High Customer Priority then phone textbox will be shown" columns="1" id="out" collapsible="false">
                <apex:inputField value="{!acc.CustomerPriority__c}" onchange="priorityChangedJavaScript()"/>
                <apex:inputField value="{!acc.Phone}" rendered="{!showPhone}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Code:

public class actionFunctionController {
    public Account acc{get;set;}
    public Boolean showPhone{get;set;}

    public actionFunctionController(){
        acc = new Account();
        showPhone = false;
    }

    public PageReference priorityChanged(){
        if(acc.CustomerPriority__c == 'High'){
            showPhone = true;
        }
        else{
            showPhone = false;
        }
        return null;
    }
}

Permanent link to this article: http://www.sfdcpoint.com/salesforce/actionfunction-visualforce-salesforce/