Sunday, 3 February 2013

Sorting Custom Picklist values


Sorting  custom picklist values prepared from controller is very easy when we use same values for both value and label of picklist
Here i am preparing picklist with same values for both value and label of the picklist.

List<user> lstuser=[select id,name from User];
Public List<Selectoption> lstoption{get;set;}

for(User uobj:lstuser){

lstoption.add(new selectoption(u.name,u.name));

}

in the above selectoption list having user name for both value and label
so we can sort this list by using "sort()" method as below.

eg:lstoption.sort();
===


But whenever the picklist doesn't have same values for value and label of piclist then

you cannot sort directly by using sort() method.Even it is applicable but it

doesn't sort your values properly.

See here in my case i have a picklist having  user Id as value and user name as label

now i need to have sort th picklist.

List<user> lstuser=[select id,name from User];
Public List<Selectoption> lstoption{get;set;}

for(User uobj:lstuser){

lstoption.add(new selectoption(u.id,u.name));

}


when you apply sort() method for the above selectoption list it is not sorting properly.

whenever we have the situation like this we need to apply some logic as shown below.

1)Make a string with the combination of username and user id with seperation of any character for splitting.
Add the string to string list for every iteration.
2)Then sort the string list.
3)After that iterate through the string list and split it to id,name assign them to selectoption list.


eg:
===

List<SelectOption> lstoptions=new List<SelectOption>();
List<String> lststring=new List<String>();

for(User uobj:lstuser){

lststring.add(uobj.name+'#'+u.id);//(1) step

}
lststring.sort();//(2) step
//(3) step
for(String s:lststring){
  List<String> luidname=s.split('#');
lstoptions.add(new selectoption(luidname[1],luidname[0]));

}

Now you can get the values in sorting order from selectoption list "lstoptions"



No comments:

Post a Comment

Best Practices for Building Prompt Templates

 Hi, The following best practices should be considered when building prompt templates: Make sure that your prompt templates are concise and ...