Understanding apex:commandButton Component in Visualforce

The <apex:commandButton> component is used to create a button that invokes a controller action when clicked. It’s commonly used for operations like form submission, saving records, or navigating to another page.


Syntax

xmlCopyEdit<apex:commandButton value="Save" action="{!saveRecord}" />

Key Attributes

AttributeDescription
valueText displayed on the button.
actionThe controller method to call when clicked.
immediateOptional. Skips validation if set to true.
disabledOptional. Disables the button.
styleClassOptional. CSS class for custom styling.
reRenderOptional. Rerenders specific components on the page after action completes.

Example 1: Simple Submit Button

xmlCopyEdit<apex:form>
    <apex:commandButton value="Submit" action="{!submitForm}" />
</apex:form>
  • Calls the submitForm method from the controller.

Example 2: Button With Validation Skipped

xmlCopyEdit<apex:form>
    <apex:commandButton value="Cancel" action="{!cancelForm}" immediate="true" />
</apex:form>
  • Useful for cancel buttons where form validation should be skipped.

Example 3: Button With Rerendering

xmlCopyEdit<apex:form>
    <apex:commandButton value="Save" action="{!saveData}" reRender="resultPanel" />
    <apex:outputPanel id="resultPanel">
        <apex:outputText value="{!message}" />
    </apex:outputPanel>
</apex:form>
  • After the saveData method is executed, the resultPanel is refreshed with updated content.

When to Use <apex:commandButton>

  • Use for triggering controller logic from the UI.
  • When server-side logic or navigation is required.
  • Useful in forms, modals, and data operations.

Best Practices

  • Name the controller method clearly (e.g., saveAccount, deleteRecord).
  • Use reRender to update only the required parts of the page.
  • Consider using immediate="true" cautiously, as it skips validation.