最近在写一个drupal界面,要显示一个表格,需要分页。但是drupal自带的分页都是基于SQL查询的,而我这次要做的是从mongo中查询数据显示(虽然是从mongo中查询,其实是抽象出了一个model),所以就想研究一下如何在drupal中实现不基于SQL查询的分页功能。
看了drupal官方文档,发现drupal默认的pager非常依赖于SQL查询,很难满足我的需求。后来虽然找到一个从mongo查询实现的分页,但是想了想还是决定自己写一个比较通用的工具,将来需要分页的地方多着呢!
1 function pager_without_sql($quantity, $limit, $page = 0, $url = null) { 2 global $base_path; 3 if (!$url) { 4 $url = $base_path.current_path(); 5 } 6 $total = ceil($quantity / $limit); 7 $first_page = 0; 8 $last_page = $total - 1; 9 $cur_page = $page; 10 $previous_page = $cur_page - 1 > $first_page ? $cur_page - 1 : $first_page; 11 $next_page = $cur_page + 1 < $last_page ? $cur_page + 1 : $last_page; 12 $start_page = $cur_page - 4 > $first_page ? $cur_page - 4 : $first_page; 13 $end_page = $cur_page + 4 < $last_page ? $cur_page + 4 : $last_page; 14 $page_array = array(); 15 $page_array[‘first‘] = array( 16 ‘page‘ => $first_page, 17 ‘name‘ => ‘首页‘, 18 ‘link‘ => $url . ‘?page=‘ . $first_page, 19 ‘class‘ => ‘pager-first‘ 20 ); 21 $page_array[‘previous‘] = array( 22 ‘page‘ => $previous_page, 23 ‘name‘ => ‘上一页‘, 24 ‘link‘ => $url . ‘?page=‘ . $previous_page, 25 ‘class‘ => ‘pager-previous‘ 26 ); 27 if ($start_page > $first_page) { 28 $page_array[‘before_start‘] = array( 29 ‘page‘ => ‘‘, 30 ‘name‘ => ‘...‘, 31 ‘link‘ => ‘‘, 32 ‘class‘ => ‘pager-ellipsis‘ 33 ); 34 } 35 for ($i = $start_page; $i <= $end_page; $i++) { 36 $page_array[$i] = array( 37 ‘page‘ => $i, 38 ‘name‘ => $i + 1, 39 ‘link‘ => ($i == $cur_page ? ‘‘ : $url . ‘?page=‘ . $i), 40 ‘class‘ => ‘pager-item‘ 41 ); 42 } 43 if ($end_page < $last_page) { 44 $page_array[‘after_end‘] = array( 45 ‘page‘ => ‘‘, 46 ‘name‘ => ‘...‘, 47 ‘link‘ => ‘‘, 48 ‘class‘ => ‘pager-ellipsis‘ 49 ); 50 } 51 $page_array[‘next‘] = array( 52 ‘page‘ => $next_page, 53 ‘name‘ => ‘下一页‘, 54 ‘link‘ => $url . ‘?page=‘ . $next_page, 55 ‘class‘ => ‘pager-next‘ 56 ); 57 $page_array[‘last‘] = array( 58 ‘page‘ => $last_page, 59 ‘name‘ => ‘末页‘, 60 ‘link‘ => $url . ‘?page=‘ . $last_page, 61 ‘class‘ => ‘pager-last‘ 62 ); 63 if ($total > 1) { 64 foreach ($page_array as $index => $page) { 65 $items[$index] = array( 66 ‘class‘ => array($page[‘class‘]), 67 ‘data‘ => $page[‘link‘]?‘<a href="‘.$page[‘link‘].‘">‘.$page[‘name‘].‘</a>‘:$page[‘name‘], 68 ); 69 } 70 $pager_string = ‘<h2 class="element-invisible">‘ . t(‘Pages‘) . ‘</h2>‘ . theme(‘item_list‘, array( 71 ‘items‘ => $items, 72 ‘attributes‘ => array(‘class‘ => array(‘pager‘)), 73 )); 74 $pager_form = array( 75 ‘#markup‘ => $pager_string, 76 ); 77 return $pager_form; 78 } 79 }
传入的参数就是数据总条数、每页条数、当前页数。将返回的pager放到form里就OK啦。页码是通过get方式传递的,查询中的limit就要自己注意啦。
小白一只,还请大家多多指教!
时间: 2024-10-13 11:13:51