logo





GradeBook released!
Oct, 2008
Solstice adds a grade book to its toolkit!

New Versions!
April, 2008
A new version of all our software is available!

CommonView Released
April, 2008
Check out our latest collaborative tool.

RESTful Web Services
Jan, 2008
Solstice provides support for RESTful development.

How to use SortService

The basics

SortService is a great, easy way to bring sorting to any page that has a list of data.

Perl
use constant SORT_FIELD => 'home_sort_field'; use constant SORT_DIR => 'home_sort_direction'; my $pref_service = Solstice::PreferenceService->new(); my $sort_service = Solstice::SortService->new($pref_service, SORT_FIELD, SORT_DIR);

SortService takes three arguments, a preference service in which to store the data and key names for field and direction preference.

Now we need to add our sort field using the addSortField function. This function takes a hash.

Perl
$sort_service->flush(); $sort_service->addSortField({ label => $lang_service->getString('title_name_header'), button_name => 'sort_by_title', action => 'sort', sort_func => sub { lc($a->getTitle()) cmp lc($b->getTitle()) }, default => 1, });

The flush method is required if you are running this code in a controller, because many controller functions are run twice per click.

Perl
button_name => 'sort_by_title',

This is the name of the button that can be used in your template.

Perl
sort_func => sub { lc($a->getTitle()) cmp lc($b->getTitle()) },

The sort_func takes an anonymous sub. This is where you actually define your sorting algorithm.

There is one optional field, default. You may specify many sort fields, but only one may be the default. If a user is coming to this page for the first time, the default sort field will be the field your list is sorted on.

Now we need to hook up the sort service with our list.

Perl
my $list = $self->getModel(); my $iterator = $list->iterator(); $iterator->sort($sort_service->getSortMethod());

At this point we are almost done getting our sorting set up. SortService has all of its sort fields defined and can sort our list for us. The problem is, we have given the user no way to change sorting methods yet. We have to go into our view and add all of our sorting buttons to the template.

Perl
my %sort_links = $sort_service->getSortLinks(); foreach my $key (keys %sort_links) { $self->setParam($key, $sort_links{$key}); }

Now we can go into the template and add the sort links wherever we want. The button_name attribute given earlier corresponds directly to template variables that we just added in the view.

HTML
<!-- sol_var sort_by_title -->

API

Take a look at the pod to get a full api list.