Search code examples
salesforceapex-codevisualforce

Create a select option with current quarter and previous 11 quarters


I need to create a select box with options showing the current quarter and previous 11 quarters in my Vf page.

I dont want to hardcode them as the values would change with a new quarter. This should always default to current quarter.

Any pointers would be helpful

Thanks


Solution

  • Use apex:selectList with selectOptions to display:

    <apex:selectList value="{!quarter}" multiselect="true">
        <apex:selectOptions value="{!listOfQuarters}"/>
    </apex:selectList><p/>
    

    The controller could look like the following:

    public List<SelectOption> getListOfQuarters() {
        List<SelectOption> options = new List<SelectOption>();
    
        // non-dynamic code as an example
    
        options.add(new SelectOption('Q2 2012','Q2 2012'));
        options.add(new SelectOption('Q1 2012','Q1 2012'));
        options.add(new SelectOption('Q4 2011','Q4 2011'));
    
        return options;
    }
    

    To automatically generate the option values, I would use Datetime methods: now() to grab the current date, month() and year() to extract the month and year, and maybe use a Map to lookup the quarter by month, or divide the month number by three and use ceil() to get the current quarter.

    To create the previous 11 quarters, use addMonths() with a negative value, three months at a time inside a loop.

    myDatetime.addMonths(-3)
    

    If you are not using calendar quarters you may be able to use SOQL to query the Period object. You can definitely determine your fiscal year start month:

    SELECT FiscalYearStartMonth FROM Organization