Thursday 6 September 2012

Display a Table - Using Standard User Interface Components - Visualforce

In the previous lessons, you displayed individual fields and a complete record. Sometimes however, you need to display a set of fields across a number of records—for example, the list of contacts associated with the account. In this step you will list the contacts of an account record by iterating over the list and displaying each one individually. It may seem complex initially because there are multiple tags that nest within each other, but you will find it second nature in no time. Don’t forget you can always click the Component Reference link to learn more about each.
  1. First start by adding an <apex:pageBlock> component:
    <apex:pageBlock title="My Account Contacts">
    </apex:pageBlock>
  2. You can save and view the result if you like. Now within this component, insert another one, the <apex:pageBlockTable> component:
    <apex:pageBlockTable value="{! account.contacts}" var="item">
    </apex:pageBlockTable>
    You can think of this component as doing the following: it takes a look at its value attribute, and retrieves the list of records that it finds there. In this case, it retrieves the contactsfield that represents the list of Contact records associated with the current Account record. Then, for each individual Contact record, it assigns it to a variable called item. It does this repeatedly until it reaches the end of the list. The key lies in the body of the component. This will be output at each iteration—effectively allowing you to produce something for each individual record.
  3. Ideally, you want to insert something inside of the <apex:pageBlockTable> component that does something with the current item. Try adding this:
    <apex:column value="{! item.name}"/>
    The <apex:column> component creates a new column within the table. It adds a table header based on the name of the field, and also outputs the values for that field in the rows of the table, one row per record. In this case, you have specified {! item.name}, which will show the name field for each of the Account’s Contacts.
Representation of Contacts on an Account
Here’s what your final code looks like:
<apex:pageBlock title="My Account Contacts">
    <apex:pageBlockTable value="{! account.contacts}" var="item">
        <apex:column value="{! item.name}"/> 
    </apex:pageBlockTable> 
</apex:pageBlock>
Contact records also have a field called phone. Try adding a column to display the phone numbers. Of course, if you don’t have any contacts associated with the account that you’re viewing, or if you haven’t supplied an account ID, then it won’t display anything.

No comments:

Post a Comment