Salesforce Menu

Visualforce – fetching records from Salesforce’s sObject in Visualforce pages

We have already seen how to enter/fill the values of a record using the standard controller. But we can also display/get the field values in a more formatted.

Display Fields

Whenever we want to show the fields of a record in a formatted manner with column headers, rather than just the values and labels, we can use the OutputField tag as an option. The code given as below shows the visualforce code to display the filled data from Account Object. As you can see that we do not need the labels at our end to indicate the field values.

<apex:page standardController="Account">
  <apex:form >
    <apex:pageblock title="Account Summery">
        <apex:pageblockSection columns="3">
        <apex:outputfield value="{!Account.name}"/>
        <apex:outputfield value="{!Account.phone}"/>
        <apex:outputfield value="{!Account.fax}"/>
    </apex:pageblockSection>
       </apex:pageblock>
  </apex:form>
</apex:page>

On clicking on preview the page, we get the following output.

account-summery

Note: In URL, please supply the id which account do you want to see in visualforce page as output. As shown below:

https:<your domain>/apex/HelloVFPage?id=0012x0000052a93

Display multiple records in a table:

We can display all the records of a child/details Object by taking a value from a parent/master table. For example, we can display all the contacts object records which are associated with an account. In such case, we use the iteration component which in our case is the contacts object linked to account using lookup relationship i.e. in the below example we trying to showcase you that how to travel from Parent Object to Child Object in visualforce pages in below code we are trying to display all the contacts associated with the Account object.

Note: whenever you want to travel from parent to child object always use “Child Relationship Name” which you get from contact object’s field. Here in below example “contacts” is nothing but “Child Relationship Name” that we are referring from account i.e. account.contacts.

<apex:page standardController="account" >
<apex:form >
<apex:pageblock >
  <apex:pageblockTable value="{!account.contacts}" var="ac">
      <apex:column value="{!ac.name}"/>
     <apex:column value="{!ac.phone}"/>
  </apex:pageblockTable>
</apex:pageblock>
</apex:form>
</apex:page>

On clicking on preview the page, we get the following output.

account

Note: In URL, please supply the id of account for which contact you want to display on visuaforce page as output. As shown below:

https:<your domain>/apex/HelloVFPage?id=0012x0000052a93

Subscribe Now