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
| Attribute | Description |
|---|---|
value | Text displayed on the button. |
action | The controller method to call when clicked. |
immediate | Optional. Skips validation if set to true. |
disabled | Optional. Disables the button. |
styleClass | Optional. CSS class for custom styling. |
reRender | Optional. 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
submitFormmethod 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
saveDatamethod is executed, theresultPanelis 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
reRenderto update only the required parts of the page. - Consider using
immediate="true"cautiously, as it skips validation.