- Visualforce Development Cookbook
- Keir Bowden
- 387字
- 2025-04-04 22:25:05
Editing a record in Visualforce
The standard record edit page does not allow customization outside the layout of fields. Editing records with Visualforce pages allows customization of all aspects of the page, including styling, content, and displayed buttons.
In this recipe, we will create a Visualforce page that provides contact edit capability, but does not allow a contact to be reparented to a different account. The account lookup field is editable until the record is saved with the lookup populated, after which it becomes read-only. This page will also render a different section heading depending on whether the contact is being created or edited.
Getting ready
This recipe makes use of a standard controller, so we only need to create the Visualforce page.
How to do it…
- Navigate to the Visualforce setup page by clicking on Your Name | Setup | Develop | Pages.
- Click on the New button.
- Enter
ContactCreateEdit
in the Label field. - Accept the default ContactCreateEdit that is automatically generated for the Name field.
- Paste the contents of the
ContactCreateEdit.page
file from the code download into the Visualforce Markup area and click on the Save button. - Navigate to the Visualforce setup page by clicking on Your Name | Setup | Develop | Pages.
- Locate the entry for the ContactCreateEdit page and click on the Security link.
- On the resulting page, select which profiles should have access and click on the Save button.
How it works…
Opening the following URL in your browser displays the ContactCreateEdit page to create a new record: https://<instance>/apex/ContactCreateEdit
.
Here, <instance>
is the Salesforce instance specific to your organization, for example, na6.salesforce.com.

Note that the section heading for the page is Create Contact, and the Account Name field is editable. Save this record and edit it again via the same page using the following URL: https://<instance>/apex/ContactCreateEdit?id=<contact_id>
.
Here, <contact_id>
is the record ID of the newly created contact, and it displays the edit form of the page with a different section heading, and the Account Name field is changed to read-only.

The Visualforce page utilizes a standard controller and conditionally renders the section heading, and input/output variants of the Account Name field based on the ID of the record.
<apex:sectionHeader title="{!IF (Contact.id==null, 'Create', 'Edit')} Contact" /> <apex:inputField value="{!Contact.AccountId}" rendered="{!null==Contact.AccountId}" /> <apex:outputField value="{!Contact.AccountId}" rendered="{!null!=Contact.AccountId}" />
See also
- The Using field sets recipe in this chapter shows how an administrator can control the editable fields on a Visualforce page.