Play Games

Search This Blog

Sunday, January 5, 2014

Display list of accounts group by picklist field value in visualforce page.

Sometimes we may have the requirement of displaying records of any object group by picklist field value.
In order to do this u need to generate 2 lists one is list of records and other is list of picklist field values.Then in visualforce page u can use nested <apex:repeat> and some conditions to display the records group by picklist field value.

The example below will explain it.
Here is the code for Apex Class:

public with sharing class GroupBy{
 
  public List<account> accounts {get;set;}  
  public Account ac {get;set;}
  public String[] states {get;set;}
  id x;
  public GroupBy()
  {
    ac = [ select Name FROM Account 
    WHERE id = :ApexPages.currentPage().getParameters().get('id')];
     x=ac.id;
  }
  public id getQuantity1() {
     
        return x;
    } 
 
  public void load() {
  List<String> lstPickvals=new List<String>();
  Schema.DescribeFieldResult fieldResult = 
account.active__c.getDescribe();
  List<Schema.PicklistEntry> ple =fieldResult.getPicklistValues();
  system.debug('....'+ple );
  for (Schema.PicklistEntry a:ple ){//forall values in picklist list
      lstPickvals.add(a.getValue());//add value to our final list
   }
   system.debug('....'+lstPickvals);
    // for demo purposes limit the states  
    accounts = [Select ID, Name,active__c From account
      Where Active__c IN: lstPickvals];
 
    // dynamically create set of unique states from query
    Set<String> stateSet = new Set<String>();
    for (account a : accounts)
      stateSet.add(a.Active__c);
 
    // convert the set into a string array  
    states = new String[stateSet.size()];
    Integer i = 0;
    for (String state : stateSet) { 
      states[i] = state;
      i++;
    }
 
  }
 
}
The code for visualforce page:

<apex:page controller="GroupBy" action="{!load}" sidebar="false">
 <apex:sectionHeader title="My Sample Display Page" 
subtitle="Group by picklist field value" description=
"shows how you can dynamically group results by field value."/>
 
 <apex:repeat value="{!states}" var="state">
 
 <apex:pageBlock title="{!state}">
 
  <apex:repeat value="{!accounts}" var="account"> 
<apex:outputPanel rendered="{!IF(state=account.Active__c,true,false)}">
    {!account.Name} - {!account.Active__c}<br/>
</apex:outputPanel>
 
   </apex:repeat>
 
    </apex:pageBlock>
 
  </apex:repeat>
 {x}
</apex:page>
 
When we run the visualforce page with accountid,
the output will be as follows
 
 
 
 
 
 
 
 



 


No comments:

Post a Comment