webmcp

view framework/env/ui/paginate.lua @ 8:f02e14d1e69e

Bugfix: Negative offset when paginating empty result set
author jbe
date Sun Jan 31 18:36:35 2010 +0100 (2010-01-31)
parents 72860d232f32
children d76a8857ba62
line source
1 --[[--
2 ui.paginate{
3 selector = selector, -- a selector for items from the database
4 per_page = per_page, -- items per page, defaults to 10
5 name = name, -- name of the CGI get variable, defaults to "page"
6 page = page, -- directly specify a page, and ignore 'name' parameter
7 content = function()
8 ... -- code block which should be encapsulated with page selection links
9 end
10 }
12 This function preceeds and appends the output of the given 'content' function with page selection links. The passed selector will be modified to show only a limited amount ('per_page') of items. The currently displayed page will be determined directly by cgi.params, and not via the param.get(...) function, in order to pass page selections automatically to sub-views.
14 --]]--
16 function ui.paginate(args)
17 local selector = args.selector
18 local per_page = args.per_page or 10
19 local name = args.name or 'page'
20 local content = args.content
21 local count_selector = selector:get_db_conn():new_selector()
22 count_selector:add_field('count(1)')
23 count_selector:add_from(selector)
24 count_selector:single_object_mode()
25 local count = count_selector:exec().count
26 local page_count = 1
27 if count > 0 then
28 page_count = math.floor((count - 1) / per_page) + 1
29 end
30 local current_page = atom.integer:load(cgi.params[name]) or 1
31 if current_page > page_count then
32 current_page = page_count
33 end
34 selector:limit(per_page)
35 selector:offset((current_page - 1) * per_page)
36 local id = param.get_id_cgi()
37 local params = param.get_all_cgi()
38 local function pagination_elements()
39 if page_count > 1 then
40 for page = 1, page_count do
41 if page > 1 then
42 slot.put(" ")
43 end
44 params[name] = page
45 local attr = {}
46 if current_page == page then
47 attr.class = "active"
48 end
49 ui.link{
50 attr = attr,
51 module = request.get_module(),
52 view = request.get_view(),
53 id = id,
54 params = params,
55 text = tostring(page)
56 }
57 end
58 end
59 end
60 ui.container{
61 attr = { class = 'ui_paginate' },
62 content = function()
63 ui.container{
64 attr = { class = 'ui_paginate_head ui_paginate_select' },
65 content = pagination_elements
66 }
67 ui.container{
68 attr = { class = 'ui_paginate_content' },
69 content = content
70 }
71 ui.container{
72 attr = { class = 'ui_paginate_foot ui_paginate_select' },
73 content = pagination_elements
74 }
75 end
76 }
77 end

Impressum / About Us