1 package Reaction::UI::ViewPort::Collection::Role::Order;
5 use namespace::clean -except => [ qw(meta) ];
6 use MooseX::Types::Moose qw/Int HashRef Str ArrayRef/;
7 has enable_order_by => (is => 'rw', isa => ArrayRef);
8 has coerce_order_by => (is => 'rw', isa => HashRef);
13 trigger_adopt('order_by'),
14 clearer => 'clear_order_by'
17 has order_by_desc => (
20 trigger_adopt('order_by'),
24 sub _build_order_by_desc { 0 }
27 shift->clear_current_collection;
31 my ($self,$order_by) = @_;
32 return 1 unless $self->has_enable_order_by;
33 return scalar grep { $order_by eq $_ } @{ $self->enable_order_by };
36 sub _order_search_attrs {
39 if ($self->has_order_by) {
40 my $order_by = $self->order_by;
41 if( $self->has_coerce_order_by ){
42 $order_by = $self->coerce_order_by->{$order_by}
43 if exists $self->coerce_order_by->{$order_by};
45 my $key = $self->order_by_desc ? '-desc' : '-asc';
46 $attrs{order_by} = { $key => $order_by };
51 after clear_order_by => sub {
53 $self->order_by_desc(0);
54 $self->clear_current_collection;
57 around _build_current_collection => sub {
60 my $collection = $orig->(@_);
61 return $collection->where(undef, $self->_order_search_attrs);
64 around accept_events => sub { ('order_by', 'order_by_desc', shift->(@_)); };
72 Reaction::UI::ViewPort::Collection::Role::Order - Order support for collections
76 Role to add order support to collection viewports.
80 =head2 enable_order_by
82 Re-writable array reference. Optionally use this to manually specify a list of
83 fields that support ordering, instead of the default of all fields. This is
84 useful to exclude computed values or non-indexed columns from being sortable.
86 =head2 coerce_order_by
88 Re-writeable hash reference. Optionally use this to manually specify the way in
89 which a field should be ordered. This is useful when the field name and the
90 query to sort it differ. E.g. for a belongs_to item:
92 coerce_order_by => { foo => ['foo.last_name', 'foo.first_name'] },
96 Re-writeable string. Optionally set it to dictate which field to use when
101 Re-writeable boolean. Optionally use descending order when sorting. Defaults to false.
105 =head2 can_order_by $field_name
107 Returns true if sorting by that field is supported, false otherwise.
111 See L<Reaction::Class> for authors.
115 See L<Reaction::Class> for the license.