+ Start a Discussion
LearnerrrLearnerrr 

Want to sort name of countries .List is provided ,now I want on the top usa and uk and then sorted list of other countries ..How I can do this

Best Answer chosen by Learnerrr
Khan AnasKhan Anas (Salesforce Developers) 

Hi Sweta,

Greetings to you!

Below is the sample code which I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Visualforce:
<apex:selectList value="{!country}" size="1">
      <apex:selectOptions value="{!Countries}" />
   </apex:selectList>

Controller:
public List<SelectOption> getCountries(){
    optionsCountryMainList = new list<SelectOption>();
    optionsCountrySubList = new list<SelectOption>();

    optionsCountryMainList.add(new SelectOption('', '-- Select Country --', true)); 

    optionsCountryMainList.add(new SelectOption('USA','USA'));
    optionsCountryMainList.add(new SelectOption('UK','UK'));

    for(Country__c country : [SELECT Id, Name From Country__c]){
        if(country.Name !='USA' && country.Name !='UK')
        optionsCountrySubList.add(new SelectOption(country.Name, country.Name));
    }


    optionsCountrySubList.sort();  
    optionsCountryMainList.addAll(optionsCountrySubList);
    return optionsCountryMainList;
}

Or you can use Order By in SOQL.
 
public List<SelectOption> getCountries(){
        optionsCountryMainList = new list<SelectOption>();
        optionsCountrySubList = new list<SelectOption>();

        optionsCountryMainList.add(new SelectOption('', '-- Select Country --', true)); 

        optionsCountryMainList.add(new SelectOption('USA','USA'));
        optionsCountryMainList.add(new SelectOption('UK','UK'));

        for(Country__c country : [SELECT Id, Name From Country__c order by Name]){
            if(country.Name !='USA' && country.Name !='UK')
            optionsCountrySubList.add(new SelectOption(country.Name, country.Name));
        }

        optionsCountryMainList.addAll(optionsCountrySubList);
        return optionsCountryMainList;
    }

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas