this is my dataProvider in my Controller:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['NumeroInElenco' => SORT_ASC]],
'pagination' => [
'pageSize' => 10,
],
]);
$this->load($params);
Now I can visualize 10records in my grid, and this is good. But there is a problem, when I activate the button toggle data (to show all records and not only the firts 10), if I export the data the excel file returns me only the firts 10. I think that the reason is the pageSize declaration. How I can fix this problem??
I hope to be clear, I have to solve it quickly.
Set Pagination to false to get all records in export.
$dataProvider->pagination = false;
public function actionIndex()
{
$product = Product::find()->where(['show' => 1]);
$pages = new Pagination(['totalCount' => $product->count()]);
$pages->pageSize = 3;
$pages->pageSizeParam = false;
$model=$product->offset($pages->offset)->limit($pages->limit)->all();
return $this->render('index', ['product' => $model, 'page' => $pages]);
}
Related
I'm trying to create the menu link programmatically. But its not working where source language is other than english. Here is my code.
$language_list = language_list();
foreach ($language_list as $language_code => $language_object) {
$menu_item = array(
'link_title' => t('Fruit'),
'menu_name' => 'menu-main-footer',
'customized' => 1,
'link_path' => $custom_path,
'language' => $language_code,
'weight' => 30,
);
menu_link_save($menu_item);
}
Any one have some idea on this?
I changed my code. And it work for me.
// Create menu translation set.
$menu_translation_set = i18n_translation_set_create('menu_link');
// Create translated menu link for all site enable language.
$language_list = language_list();
foreach ($language_list as $language_code => $language_object) {
// Add Fruit link in menu-main-footer.
// 'change-fruit' is node title.
$fruit_path = drupal_get_normal_path('change-fruit', $language_code);
if (!menu_link_get_preferred($fruit_path, 'menu-main-footer')) {
$menu_item = array(
'link_title' => t('fruit'),
'menu_name' => 'menu-main-footer',
'customized' => 1,
'link_path' => $fruit_path,
'language' => $language_code,
'weight' => 30,
'i18n_tsid' => $menu_translation_set->tsid,
);
menu_link_save($menu_item);
$menu_translation_set->add_item($menu_item, $language_code);
$menu_translation_set->save();
}
}
May be helpful to other.
I had to migrate an old menu to a new one with its localized translations so here is what I did :
$old_name = 'menu-old';
$new_name = 'menu-new';
$old_menu = menu_load($old_name);
if(isset($old_menu)){
$old_mlids = db_query("SELECT mlid from {menu_links} WHERE menu_name=:menu_name", array(':menu_name' => $old_name))->fetchAll();
if(!empty($old_mlids)){
// Clean existing items in new menu.
$new_mlids = db_query("SELECT mlid from {menu_links} WHERE menu_name=:menu_name", array(':menu_name' => $new_name))->fetchAll();
if(!empty($new_mlids)){
foreach($new_mlids as $record){
menu_link_delete($record->mlid);
}
}
// Copy old to new menu.
foreach($old_mlids as $record){
$old_menu_item = menu_link_load($record->mlid);
$new_menu_item_config = array(
'link_title' => $old_menu_item['link_title'],
'link_path' => $old_menu_item['link_path'],
'menu_name' => $new_name,
'customized' => 1,
'weight' => $old_menu_item['weight'],
'expanded' => $old_menu_item['expanded'],
'options' => $old_menu_item['options'],
);
$new_menu_item = $new_menu_item_config;
menu_link_save($new_menu_item);
// Migrate translations.
$languages = language_list('enabled')[1];
foreach($languages as $lang_code => $language_object){
if ($lang_code == language_default('language')) {
continue;
}
$translation_value = i18n_string_translate('menu:item:'.$old_menu_item['mlid'].':title', $old_menu_item['link_title'], array('langcode' => $lang_code));
if($translation_value != $old_menu_item['link_title']){
i18n_string_translation_update('menu:item:'.$new_menu_item['mlid'].':title', $translation_value, $lang_code, $old_menu_item['link_title']);
}
}
}
}
// Delete old menu.
menu_delete(array('menu_name' => $old_name));
}
I am trying to use Pagination after union of two queries the pagination does not seems to work. However if I try to make one queries without union it works.
The below are the queries.Please help.
//First Query
$first_second = $this->find()->select($strcolumn.', p.featured_name')->from(MYDIRECTORY::tableName().' j')->join('INNER JOIN' ,MYDIRECTORYFEATUREDCLASS::tableName().' p', 'p.featurer_id = j.listdetails_featured_frid')->where(['listdetails_list_frid' => $id['list_id']])->andWhere(['<=', 'listdetails_featured_frid', 2])->andWhere(['listdetails_list_flag' => MYDIRECTORYCLASS::STATUS_ACTIVE])->orderBy(['listdetails_featured_frid'=>SORT_ASC,'listdetails_list_pos'=>new Expression('rand()')]);
//Second Query
$second_list = $this->find()->select($strcolumn.', p.featured_name')->from(MYDIRECTORYCLASS::tableName().' j')->join('INNER JOIN' ,MYDIRECTORYFEATUREDCLASS::tableName().' p', 'p.featurer_id = j.listdetails_featured_frid')->where(['listdetails_list_frid' => $id['list_id']])->andWhere(['>', 'listdetails_featured_frid', 2])->andWhere(['listdetails_list_flag' => MYDIRECTORYCLASS::STATUS_ACTIVE])->orderBy(['listdetails_featured_frid'=>SORT_ASC,'listdetails_list_medname'=>SORT_ASC]);
//Joined Union Query
$joinedquerys=$first_second->union($second_list);
$countQuery = clone $joinedquerys;
$pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => \Yii::$app->params['pagination_limit'],'defaultPageSize' => \Yii::$app->params['pagination_limit'],'forcePageParam' => false,'params' => ['page' => \Yii::$app->request->get('page', 1)] ]);
$resultArray = $joinedquerys->offset($pages->offset)->limit($pages->limit)->asArray()->all();
return $this->render('listing', [
"mylisting" => $resultArray,
"pagination" => $pages
]);
While using the pagination as below , the pagination seems to not work?Any help will be greatly appreciated
echo LinkPager::widget([
'pagination' => $pagination,
'options' => ['class' => 'paginate pag2 clearfix'],
'registerLinkTags' => true,
'prevPageLabel' => \YII::$app->params['linker_page_btn_prev'],
'nextPageLabel' => \YII::$app->params['linker_page_btn_next'],
'maxButtonCount' => \YII::$app->params['linker_page_btn_count'],
'activePageCssClass' => 'current',
'nextPageCssClass' => 'next'
]);
you could use dataProvider
<?php
$joinedquerys=$first_second->union($second_list);
$dataProvider = new SqlDataProvider([
'sql' => $joinedquerys,
]);
?>
I had the same problem, but in addition I had to use the ActiveDataProvider. To achieve this I had to do the following:
$joinedQuery = $first_second->union($second_list);
$dirQuery = MYDIRECTORY::find()->from(['directories' => $joinedQuery]);
$provider = new ActiveDataProvider([
'query' => $dirQuery,
]);
Hope this helps someone :)
I am looking to set a condition only for a single action in the controller, so I don't want to change my search model.
My code looks like this:
public function actionRoles()
{
$searchModel = new EmployeeSearch();
//$searchModel->query()->where('role <> regular');
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('view_role', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
The commmented row shows my condition ($searchModel->query()->where('role <> regular');), it's pretty straightforward but I have not found a solution that works online.
For reference I tried those:
Yii2 how does search() in SearchModel work?
Yii2 Modify find() Method in Model search()
https://github.com/yiisoft/yii2/issues/5668
criteria Active data provider in Yii 2
Ok, I got it done, it works this way for me:
public function actionRoles()
{
$searchModel = new EmployeeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->sort = ['defaultOrder' => ['role'=>SORT_ASC, 'fullname'=>SORT_ASC]];
$dataProvider->query->where('employee.role <> \'regular\'');
return $this->render('view_role', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Certainly a bit complicated and doing it in the model would probably be better, but I only want it to use it in this action and have a bunch of other actions with the same searchmodel but different conditions.
You can do it this way in the Controller
$searchModel = new ModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andWhere(['lang'=>'ENG']);
You can try this way
$searchModel = new EmployeeSearch();
$searchModel->role = 'regular';
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
In Search model :
$query->andFilterWhere(['<>', 'role', $this->role]);
Second way pass second parameter like :
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $role = 'regular');
In search model
if($role == 'regular') {
$query->andWhere(['<>', 'role', $this->role]);
}
Another way pass other parameter like but problem in filter time:
$dataProvider = $searchModel->search(Yii::$app->request->queryParams+['EmployeeSearch' => ['<>', 'role' =>'regular']]);
You can try this:
SearchModel:
$searchModel = new EmployeeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$query->andFilterWhere(['<>', 'role'=>'regular']);
return $this->render('view_role', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
Please also visit this link:http://www.yiiframework.com/doc-2.0/guide-output-data-providers.html
Try this solution
$searchModel = new ModelnameSearch
(
[ 'Attribute' => 1,
'SecondAttribte' => '1',
]
);
Try like this using multi-params -
$searchModel = new YourSearchModel();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->where('field1 = :field1 AND field2 = :field2', [':field1' => 1, ':field2' => '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.
I want to extend default Drupal 7 node search with one additional field.
I alter search form with the following new field:
function mymodule_form_search_form_alter(&$form, &$form_state, $form_id) {
$form['basic']['site'] = array(
'#type' => 'select',
'#options' => array(
'KEY1' => 'TITLE1',
'KEY2' => 'TITLE2',
'KEY3' => 'TITLE3'
)
);
}
I have a field called field_data_field_site.field_site_value which i need to use as a filter in this search.
I've tried to read about hook_search_* functions but didn't get the idea.
My question is the following. How can I extend search form? Anyone have live examples?
The following is the best way I solve this problem.
First of all I need to alter Drupal's search block and search form with my field and define new submit function.
/**
* Implements hook_form_FORM_ID_alter().
*/
function mymodule_form_search_block_form_alter(&$form, &$form_state, $form_id) {
$form['#submit'][] = 'search_form_alter_submit';
$form['site'] = array(
'#type' => 'select',
'#options' => _options(),
'#default_value' => (($_GET['site']) ? $_GET['site'] : '')
);
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function mymodule_form_search_form_alter(&$form, &$form_state, $form_id) {
$form['#submit'][] = 'search_form_alter_submit';
$form['basic']['site'] = array(
'#type' => 'select',
'#options' => _options(),
'#default_value' => (($_GET['site']) ? $_GET['site'] : '')
);
}
function _options() {
return array(
'' => 'Select site',
'site-1' => 'Site 1',
'site-2' => 'Site 2'
);
}
Submit function will forward us to default search/node page but with our query. Page would look like search/node/Our-query-string?site=Our-option-selected.
function search_form_alter_submit($form, &$form_state) {
$path = $form_state['redirect'];
$options = array(
'query' => array(
'site' => $form_state['values']['site']
)
);
drupal_goto($path, $options);
}
Next step is to use hook_search_info (Don't forget to turn it on and set as default on admin/config/search/settings page).
/**
* Implements hook_search_info().
*/
function mymodule_search_info() {
return array(
'title' => 'Content',
'path' => 'node',
'conditions_callback' => '_conditions_callback',
);
}
Conditions callback function defined in hook_search_info. We need to provide additional queries to our search.
function _conditions_callback($keys) {
$conditions = array();
if (!empty($_REQUEST['site'])) {
$conditions['site'] = $_REQUEST['site'];
}
return $conditions;
}
Finally, hook_search_execute will filter our content by our query. I used default code from this hook with modifications I need.
/**
* Implements hook_search_execute().
*/
function mymodule_search_execute($keys = NULL, $conditions = NULL) {
// Build matching conditions
$query = db_select('search_index', 'i', array('target' => 'slave'))
->extend('SearchQuery')
->extend('PagerDefault');
$query->join('node', 'n', 'n.nid = i.sid');
// Here goes my filter where I joined another table and
// filter by required field
$site = (isset($conditions['site'])) ? $conditions['site'] : NULL;
if ($site) {
$query->leftJoin('field_data_field_site', 's', 's.entity_id = i.sid');
$query->condition('s.field_site_value', $site);
}
// End of my filter
$query
->condition('n.status', 1)
->addTag('node_access')
->searchExpression($keys, 'node');
// Insert special keywords.
$query->setOption('type', 'n.type');
$query->setOption('language', 'n.language');
if ($query->setOption('term', 'ti.tid')) {
$query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
}
// Only continue if the first pass query matches.
if (!$query->executeFirstPass()) {
return array();
}
// Add the ranking expressions.
_node_rankings($query);
// Load results.
$find = $query
->limit(10)
->execute();
$results = array();
foreach ($find as $item) {
// Build the node body.
$node = node_load($item->sid);
node_build_content($node, 'search_result');
$node->body = drupal_render($node->content);
// Fetch comments for snippet.
$node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
// Fetch terms for snippet.
$node->rendered .= ' ' . module_invoke('taxonomy', 'node_update_index', $node);
$extra = module_invoke_all('node_search_result', $node);
$results[] = array(
'link' => url("node/{$item->sid}", array('absolute' => TRUE)),
'type' => check_plain(node_type_get_name($node)),
'title' => $node->title,
'user' => theme('username', array('account' => $node)),
'date' => $node->changed,
'node' => $node,
'extra' => $extra,
'score' => $item->calculated_score,
'snippet' => search_excerpt($keys, $node->body)
);
}
return $results;
}
I'd be happy if anyone would give me a better answer.