how to create sections of grouped data in Vf page

2019-08-01 04:24发布

问题:

I have a List with data below

customer name  Make      Area
Mike           honda     Chicago
Kevin          GM        Chicago
Bill           Audi      New York
roger          Suzuki    New York

i need to display this info in Vf page with the Area as sections and name and make under it

New york
Roger          Suzuki    
Bill           Audi      

Chicago
Mike           honda     
Kevin          GM        

Any pointers on how to get this would be of great help.

Thanks Prady

回答1:

I can think of two potential ways to do this, the first (which definitely works) would be to use a wrapper class in you controller like so:

public class CArea
{
    public list<Contact> liContacts {get; set;}
    public string strAreaName {get; set;}

    public CArea(Contact sContact)
    {
        strAreaName = sContact.City;
        liContacts = new list<Contact>{sContact};
    }
}

public list<CArea> liAreas {get; set;}
private map<string, CArea> mapAreas = new map<string, CArea>();

// **snip**
// fill up the list: (assuming contacts)

for(Contact sContact : myContactList}
{
    if(mapAreas.get(sContact.City) == null)
    {
        mapAreas.put(sContact.City, new CArea(sContact));
        liAreas.add(mapAreas.get(sContact.City);
    }
    else
    {
        mapAreas.get(sContact.City).liContacts.add(sContact);
    }
}

Now liAreas has a list of CArea objects, with each one containing a list of contacts, so you can loop over this list in your page:

<apex:repeat var="a" value="{!liAreas}">
    <apex:outputText value="{!a.strName}"/>
    <apex:repeat var="c" value="{!a.liContacts}">
        <apex:outputText value="{!c.FirstName c.LastName}"/>
    </apex:repeat>
</apex:repeat>

Option #2:

This is potentially a lot simpler, but I've not tried dynamic bindings with two levels like this. Similar setup to before, but use a map of areas to list of contacts:

public map<string, list<Contact>> mapAreaToContacts {get; set;}

Filling this should be easy enough, very similar to the above code. Now use dynamic Visualforce bindings as described in the Visualforce Developer's Guide, in the section Supporting Maps and Lists.

Good luck!