I am trying to integrate pagination in kohana, but don't know how to integrate it. Following is the controller function
public function action_index() {
//setup the model and view
$_users = Model::factory('users');
$us = $_users->get_users();
$view = View::factory('users/index')->bind('user_list', $us);
$this->template->set('content',$view);
}
How can i add pagination in this function?
I found some code for pagination but couldn't integrate it. This is the function i found
$this->pagination = new Pagination(array(
'base_url' => 'users/index/',
'uri_segment' => 'page',
'total_items' => count($items->get_item_count())
Please help me
EDIT:
I tried something like
public function action_index(){
$query = DB::select()->from('user');
// count number of users
$total_users = count($query);;
// set-up the pagination
$pagination = Pagination::factory(array(
'total_items' => $total_users,
'items_per_page' => 10, // this will override the default set in your config
));
// select rows using pagination's limit&offset
$users = $query->offset($pagination->offset)->limit($pagination->items_per_page)->execute();
$view = View::factory('users/index')->bind('user_list', $users)->bind('pagination', $pagination);
$this->template->set('content',$view);
}
Now no error found but pagination not showing up. Used shadowhand's pagination module suggested by #DanielThompson
I use shadowhand's pagination module which supports Kohana 3+, just make sure you grab the same branch as your Kohana version, then add it to your modules directory.
Update your application/bootstrap.php file:
Kohana::modules(array(
// ...
'pagination' => MODPATH.'pagination'
));
Copy modules/pagination/config/pagination.php to application/config/pagination.php
In your controller action (e.g. users):
// count number of users
$total_users = ORM::factory('User')->count_all();
// set-up the pagination
$pagination = Pagination::factory(array(
'total_items' => $total_users,
'items_per_page' => 10, // this will override the default set in your config
));
// get users using the pagination limit/offset
$users = ORM::factory('User')->offset($pagination->offset)->limit($pagination->items_per_page)->find_all();
// pass the users & pagination to the view
$this->view->bind('pagination', $pagination);
$this->view->bind('users', $users);
In your view:
// loop over users
foreach($users as $user) {
// ...
}
// display pagination view using
echo $pagination;
The module comes with two views: basic or floating which is set in the config file. You could also create a custom one for your application.
Related
I'm new to cakephp2 and I need some help here.
The problem is that I have a view that displays a list of items from the database and there is a pagination button below. Instead of moving to the 2nd page by using the pagination, I want to have a single button that will allow you to display(append)10 more data list. But I'm not sure how it is called and how to implement it. Sorry for my bad explanation.
I think, you can play with limit parameter.
Somethink like this:
// in controller
<?php
function items() {
$limit = array_key_exists('n', $this->request->query) ? (int) $this->request->query['n'] : 10;
// some security check you need to add
$this->paginate = array(
'limit' => $limit
);
$items = $this->paginate($this->YourModel);
// some other code
$this->set(array(
'items' => $items,
'next_limit' => $limit + 10
));
}
?>
<?php
// in view file
// items output
foreach($items as $item) ...
// more button
echo "<a href='".$this->here."?n=".$next_limit."'>More</a>";
?>
I have a module Search in my ZF2 application. The user fills in a search form out and gets a list of courses.
Now I'm adding the pagination to the module. The paginator is basically working: I can retrieve data over it and the pagination is displayed correctly (pagelinks 1-7 for 70 found courses with the dafault setting 10 items per page).
But it's still not usable. When I click on a pagelink, the form POST data is lost. I know -- it cannot work the way, how I implemented it (see the code below). But I have no idea, how to do it correctly, in order to eep checking the form data and nonetheless be able to use pagination.
That is my code:
Table class Search\Model\CourseTable
class CourseTable {
...
// without pagination
// public function findAllByCriteria(CourseSearchInput $input) {
// with pagination
public function findAllByCriteria(CourseSearchInput $input, $pageNumber) {
...
$select = new Select();
$where = new Where();
$having = new Having();
...
// without pagination
// $resultSet = $this->tableGateway->selectWith($select);
// return $resultSet;
// with pagination
$adapter = new \MyNamespqce\Paginator\Adapter\DbSelect($select, $this->tableGateway->getAdapter());
$paginator = new \Zend\Paginator\Paginator($adapter);
$paginator->setCurrentPageNumber($pageNumber);
return $paginator;
}
...
}
Search\Controller\SearchController
class SearchController extends AbstractActionController {
public function searchCoursesAction() {
$form = $this->getServiceLocator()->get('Search\Form\CourseSearchForm');
$request = $this->getRequest();
if ($request->isPost()) {
$courseSearchInput = new CourseSearchInput();
$form->setInputFilter($courseSearchInput->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$courseSearchInput->exchangeArray($form->getData());
// without pagination
// $courses = $this->getCourseTable()->findAllByCriteria($courseSearchInput);
// with pagination
$page = $this->params()->fromRoute('page');
$paginator = $this->getCourseTable()->findAllByCriteria($courseSearchInput, $page);
} else {
$paginator = null;
}
} else {
$paginator = null;
}
return new ViewModel(array(
'form' => $form,
// without pagination
// 'courses' => $courses,
// with pagination
'paginator' => $paginator,
'cities' => ...
));
}
...
}
How to get it working?
I also have the same problem, and I have solved it. But this is not good way. May be the idea will help you.
I solved it as follow: (Search pagination for Zend tutorial album module)
I build two action in controller named "search" and "index".
Whenever the search form submitted, it always post the value to search action. Search action build the url with search parameters, and redirect to index to disply search result.
And when the pagination links clicked, then posted values are passed through url. So whenever index action ask for search parameters, it always get the values in same format.
I defined route as follows:
'album' => array(
'type' => 'segment',
'options' => array(
'route' => '/album[/:action][/:id][/page/:page][/order_by/:order_by][/:order][/search_by/:search_by]',
'constraints' => array(
'action' => '(?!\bpage\b)(?!\border_by\b)(?!\bsearch_by\b)[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
'page' => '[0-9]+',
'order_by' => '[a-zA-Z][a-zA-Z0-9_-]*',
'order' => 'ASC|DESC',
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
),
),
There is a parameter named "search_by", which will keep all search parameters as a json string. This is the point, which is not good I know, but have not find any other way yet.
"Search" action build this string as -
public function searchAction()
{
$request = $this->getRequest();
$url = 'index';
if ($request->isPost()) {
$formdata = (array) $request->getPost();
$search_data = array();
foreach ($formdata as $key => $value) {
if ($key != 'submit') {
if (!empty($value)) {
$search_data[$key] = $value;
}
}
}
if (!empty($search_data)) {
$search_by = json_encode($search_data);
$url .= '/search_by/' . $search_by;
}
}
$this->redirect()->toUrl($url);
}
And next index action decode the string, do necessary action, and also send the json string to view.
public function indexAction() {
$searchform = new AlbumSearchForm();
$searchform->get('submit')->setValue('Search');
$select = new Select();
$order_by = $this->params()->fromRoute('order_by') ?
$this->params()->fromRoute('order_by') : 'id';
$order = $this->params()->fromRoute('order') ?
$this->params()->fromRoute('order') : Select::ORDER_ASCENDING;
$page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
$select->order($order_by . ' ' . $order);
$search_by = $this->params()->fromRoute('search_by') ?
$this->params()->fromRoute('search_by') : '';
$where = new \Zend\Db\Sql\Where();
$formdata = array();
if (!empty($search_by)) {
$formdata = (array) json_decode($search_by);
if (!empty($formdata['artist'])) {
$where->addPredicate(
new \Zend\Db\Sql\Predicate\Like('artist', '%' . $formdata['artist'] . '%')
);
}
if (!empty($formdata['title'])) {
$where->addPredicate(
new \Zend\Db\Sql\Predicate\Like('title', '%' . $formdata['title'] . '%')
);
}
}
if (!empty($where)) {
$select->where($where);
}
$album = $this->getAlbumTable()->fetchAll($select);
$totalRecord = $album->count();
$itemsPerPage = 2;
$album->current();
$paginator = new Paginator(new paginatorIterator($album));
$paginator->setCurrentPageNumber($page)
->setItemCountPerPage($itemsPerPage)
->setPageRange(7);
$searchform->setData($formdata);
return new ViewModel(array(
'search_by' => $search_by,
'order_by' => $order_by,
'order' => $order,
'page' => $page,
'paginator' => $paginator,
'pageAction' => 'album',
'form' => $searchform,
'totalRecord' => $totalRecord
));
}
All the sorting and paging url contain that string.
If you know all the searching paarameters before, then you can define that at route, and pass like the same way without json string. As I have to build a common search, I have build a single string.
Source code for "Album search" is available in git hub at https://github.com/tahmina8765/zf2_search_with_pagination_example.
Live Demo: http://zf2pagination.lifencolor.com/public/album
#Sam & #automatix in the question comments are both right. My suggestion (though I'm looking for a simpler alternative) is to construct a segment route, which covers all of the options that you're likely to need and start with a standard form POST request.
Then, after the request is validated, pass the form data to the paginationControl helper as follows:
$resultsView = new ViewModel(array(
'paginator' => $paginator,
'routeParams' => array_filter($form->getData())
));
Then, in your view template, set the route parameters in the paginationControl view helper:
<?php echo $this->paginationControl($paginator, 'Sliding', 'paginator/default',
array('routeParams' => $routeParams)
) ?>
I've used array_filter here because it's a really simple way of removing any element from the form data that's null, empty or so on. That way you don't pass in extra data that you don't need.
Consider the following Silverstripe page class
<?php
class Page extends SiteTree{
static $has_many = array('OtherDataObjects' => 'DataObjectClass');
public function getSearchContext() {
$fields = new FieldSet(
new TextField('Title', 'Tour'),
new DropdownField('OtherDataObjects', 'Other Data Object', array('data', 'value')
);
$filters = array(
'Title' => new PartialMatchFilter('Title'),
'OtherDataObjects' => new PartialMatchFilter('OtherDataObjects.Title')
);
return new SearchContext(
'Page',
$fields,
$filters
);
}
}
Adding this search form to a front-end form and posting a search form always results in a [User Error] with a SQL error containing something like this at the end.
AND ("DataObjectClass_Live"."DataObjectClass_Live" LIKE 'title') ORDER BY "Sort" LIMIT 25 OFFSET 0 Table 'database DataObjectClass_Live' doesn't exist
My searchcontext search throws up an error each time I try to run a search on a has_many relationship. The versioned extension seems to be the culprit because it adds _live to all tables regardless whether the baseclass has the versioned extension or not I get the same error in SilverStripe versions 2.4.x and the latest 3.0.x versions.
Any help or pointers will be appreciated.
maybe try using an sqlQuery. something like
function SearchResults() {
$select = array('*');
$from = array('OtherDataObjects');
$where = array('OtherDataObjects:PartialMatch' => '%' . $data['Title'] . '%');
$sqlQuery = new SQLQuery($select, $from, $where);
$results = $sqlQuery->execute();
return $results;
}
$data['Title'] is to be the value from the search textbox
partial match reference: http://doc.silverstripe.org/framework/en/topics/datamodel
sql query reference: http://doc.silverstripe.org/framework/en/reference/sqlquery
I am using swftools to display filefields (Drupal 6).
Now I would like to use swftools to display the custom-url emfields (embedded media fields). For example, if my emaudio field contains the url http://example.com/myaudio.mp3. I would like to use the swftools audio player to play this mp3 file.
I know how to invoke the swftools player, if I am displaying a node that contains an emfield. I use hook_preprocess_content_field() to replace $items[0]['view'] with swf($items[0]['value']):
function mytheme_preprocess_content_field(&$vars) {
foreach ($vars['items']as $index=>$arr){
// Note:
// Emfield's custom_url video provider is called "zzz_custom_url".
// Emfield's custom_url audio provider is called "custom_url"
if ($arr['provider']=='zzz_custom_url' || $arr['provider']=='custom_url'){
$vars['items'][$index]['view'] = swf($arr['value']);
}
}
}
But I do not know how to invoke the swf player if I am displaying a view that contains an emfield. That is, I have not been able to figure out how to pull off a similar trick when I am displaying a view rather than a node. Any suggestions?
I have a solution.
I created a views template to theme my emaudio field,
views-view-field--field-my-emaudio-embed.tpl.php
Here is the content of the template:
$data = $row->{$field->field_alias};
print swf($data);
Another solution:
Create the custom formatter "SWF Emaudio", as described below. Then select this formatter to display your custom-url emaudio field, from within the cck or views UI.
function mymodule_field_formatter_info() {
$formatters = array();
$formatters['swf_emaudio'] = array(
'label' => t('SWF Emaudio'),
'field types' => array('emaudio'),
);
}
function mymodule_theme() {
$themes['mymodule_formatter_swf_emaudio'] = array(
'arguments' => array('element' => NULL, 'options' => array()),
'function' => 'theme_o4_mediatools_formatter_swf_emaudio',
);
}
return ($themes);
}
function theme_mymodule_formatter_swf_emaudio($element, $options = array()) {
$embed_value = $element['#item']['value'] ;
$output = swf($embed_value, $options);
return ($output);
}
I need to define the order of the $links output
now I have 2 modules displaying its contents on that:
comments and addthis
where can I define the order of the and modify it's settings for nodes...
even customize a little bit the display?
Edit: links weights can be changed using http://drupal.org/project/linkweights
I am not sure there is any kind of UI for reordering/customizing the node links.
However you can accomplish this in a couple of ways:
Create a custom module that implements hook_link_alter() and perform the customizations.
/**
* hook_link_alter() implementation
* for more details see
* http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_link/6
* http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_link_alter/6
*/
function mymodule_link_alter(&$links, $node) {
foreach ($links as $link => $values) {
// do something with $link
}
return $links;
}
You can go even further and create an administration page that will get all the links, output them in a sortable table (a la /admin/build/block) and save the order in a variable. Ah, your module needs to have the highest weight in order to catch all the other links.
--OR--
Modify your theme's template.php and add the mytheme_preprocess_node() function or edit it or phptemplate_preprocess_node() if it exists
function phptemplate_preprocess_node(&$vars) {
$links= $vars['node']->links;
// uncomment the next line to see the current links
//var_dump($links);
// add a new link
$link_all = array(
'title' => 'See all nodes',
'href' => PATH,
//'attributes' => array('class' => 'link_class', 'id' => 'link_id', 'title' => 'link title'),
);
$links['link_all'] = $link_all;
//Modify an existing link. in this case the above added one
$links['link_all']['title'] = t('This is my custom text');
$vars['links'] = theme_links($links);
}
To reorder see http://drupal.org/node/44435#comment-861385