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.
Here’s what your final code looks like:
- First start by adding an <apex:pageBlock> component:
<apex:pageBlock title="My Account Contacts"> </apex:pageBlock>
- 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. - 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}"/>
<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