Show "page=1" params in Yii CLinkPager first page link - yii

I want to make a CListView that remembers search form input. My application saves every search input (and the current page viewed by user) into user session and add the search id into the pagination params.
$pagination = array(
'pageVar' => 'page',
'currentPage' => $currentPage - 1,
'params' => array(
'search' => $searchId,
)
);
But since the first page link at the CLinkPager don't show 'page=1' parameter, everytime I click the link from other page (say page 2), the application will think that I need the current 'search' (whose current page value is 2).
To rephrase the question, is there any way to make CLinkPager shows param 'page=1' at the first page link? Or do you have another suggestion on handling this :)
Thanks
Edited
My overall code is below. If you want to give a better suggestion, please do :)
public function actionIndex() {
$model = new User();
if (isset($_POST['User'])) {
$model->setAttributes($_POST['User']);
} else {
if (isset($_GET['search'])) {
$searchId = $_GET['search'];
//Just getting a variable stored in the session
//array(
// $searchId => array(
// 'model' => $model //the search model
// 'pageSize' => $pageSize //current pagination page size
// 'currentPage' => $currentPage //the search model
// )
//);
$search = Yii::app()->user->getSearch($searchId);
$model->setAttributes($search['model'], false);
$currentPage = $search['currentPage'];
$pageSize = $search['pageSize'];
} else {
//create default search
}
}
//Managing pageSize parameter
if (isset($_GET['pageSize'])) { //Check whether there is pageSize in $_GET parameters
if (in_array($_GET['pageSize'], $this->getPageSizes())) {
$pageSize = $_GET['pageSize'];
} else {
$pageSize = self::DEFAULT_SEARCH_PAGESIZE;
}
} else if (!isset($pageSize)) { //Check whether pageSize is already defined before
$pageSize = self::DEFAULT_SEARCH_PAGESIZE;
}
//Managing currentPage parameter
if (isset($_GET['page'])) { //Check whether there is page parameter in $_GET parameter
$currentPage = $_GET['page'];
} else if (!isset($currentPage)) { //Check whether page is already defined before
$currentPage = self::DEFAULT_CURRENT_PAGE;
}
//Saving all into new session
$newSearch = array(
'model' => $model->getAttributes(),
'currentPage' => $currentPage,
'pageSize' => $pageSize,
);
//Check whether if there is a search before and if it exists check whether the two search is the same
if (!isset($search) || (serialize($search) != serialize($newSearch))) {
//Saves into session
$searchId = Yii::app()->user->saveSearch($newSearch);
} //else use the old search id
//-----------------------------------------------------
//Building the search
//Setting criteria
$criteria = new CDbCriteria(array(
'select' => array(
'*', //just to simplify things
),
));
//Appending criteria to search model used
$criteria = $model->search($criteria);
//Appending pagination to current variables
$pagination = array(
'pageSize' => $pageSize,
'pageVar' => 'page',
'currentPage' => $currentPage - 1,
'params' => array(
'search' => $searchId, //include the search ID in the link pager request URL
)
);
//Creating dataProvider for the search
$dataProvider = new CActiveDataProvider('Property', array(
'criteria' => $criteria,
'pagination' => $pagination,
));
//Rendering
$this->render('index', array(
'dataProvider' => $dataProvider,
'pageSize' => $pageSize,
'model' => $model,
'searchId' => $searchId,
));
}

You could probably extend CPagination by modifying the createPageUrl method and remove/change the if($page>0) condition to always be true. (Or better yet, add an additional parameter to turn on/off that behavior.)

Related

Prestashop 1.7.7 - HelperForm in a Multistore Context

I'm testing a first simple version for a Multistore-compatible module. It has just two settings, which have to be saved differently depending on the current shop Context (a single shop mainly).
Now, I know that from 1.7.8 there are additional checkbox for each setting in the BO Form, but I have to manage to get it work also for 1.7.7.
Now, both Configuration::updateValue() and Configuration::get() should be multistore-ready, meaning that they update or retrieve the value only for the current context, so it should be fine.
The weird thing is that, after installing the test module, if I go to the configuration page, it automatically redirects to an All-Shop context and, if I try to manually switch (from the dropdown in the top right), it shows a blank page. Same thing happens if I try to deactivate the bottom checkbox "Activate this module in the context of: all shops".
Here is my code:
class TestModule extends Module
{
public function __construct()
{
$this->name = 'testmodule';
$this->tab = 'front_office_features';
$this->version = '1.0.0';
$this->author = 'Test';
$this->need_instance = 1;
$this->ps_versions_compliancy = [
'min' => '1.7.0.0',
'max' => '1.7.8.0',
];
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l("Test Module");
$this->description = $this->l('Collection of custom test extensions');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
if (!Configuration::get('TESTM_v')) {
$this->warning = $this->l('No version provided');
}
}
public function install()
{
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
return (
parent::install()
&& $this->registerHook('header')
&& $this->registerHook('backOfficeHeader')
&& Configuration::updateValue('TESTM_v', $this->version)
);
}
public function uninstall()
{
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
return (
parent::uninstall()
&& $this->unregisterHook('header')
&& $this->unregisterHook('backOfficeHeader')
&& Configuration::deleteByName('TESTM_v')
);
}
public function getContent()
{
// this part is executed only when the form is submitted
if (Tools::isSubmit('submit' . $this->name)) {
// retrieve the value set by the user
$configValue1 = (string) Tools::getValue('TESTM_CONFIG_1');
$configValue2 = (string) Tools::getValue('TESTM_CONFIG_2');
// check that the value 1 is valid
if (empty($configValue1)) {
// invalid value, show an error
$output = $this->displayError($this->l('Invalid Configuration value'));
} else {
// value is ok, update it and display a confirmation message
Configuration::updateValue('TESTM_CONFIG_1', $configValue1);
$output = $this->displayConfirmation($this->l('Settings updated'));
}
// check that the value 2 is valid
Configuration::updateValue('TESTM_CONFIG_2', $configValue2);
$output = $this->displayConfirmation($this->l('Settings updated'));
}
// display any message, then the form
return $output . $this->displayForm();
}
public function displayForm()
{
// Init Fields form array
$form = [
'form' => [
'legend' => [
'title' => $this->l('Settings'),
],
'input' => [
[
'type' => 'text',
'label' => $this->l('Custom CSS file-name.'),
'name' => 'TESTM_CONFIG_1',
'size' => 20,
'required' => true,
],
[
'type' => 'switch',
'label' => $this->l('Enable custom CSS loading.'),
'name' => 'TESTM_CONFIG_2',
'is_bool' => true,
'desc' => $this->l('required'),
'values' => array(
array(
'id' => 'sw1_on',
'value' => 1,
'label' => $this->l('Enabled')
),
array(
'id' => 'sw1_off',
'value' => 0,
'label' => $this->l('Disabled')
)
)
],
],
'submit' => [
'title' => $this->l('Save'),
'class' => 'btn btn-default pull-right',
],
],
];
$helper = new HelperForm();
// Module, token and currentIndex
$helper->table = $this->table;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex . '&' . http_build_query(['configure' => $this->name]);
$helper->submit_action = 'submit' . $this->name;
// Default language
$helper->default_form_language = (int) Configuration::get('PS_LANG_DEFAULT');
// Load current value into the form or take default
$helper->fields_value['TESTM_CONFIG_1'] = Tools::getValue('TESTM_CONFIG_1', Configuration::get('TESTM_CONFIG_1'));
$helper->fields_value['TESTM_CONFIG_2'] = Tools::getValue('TESTM_CONFIG_2', Configuration::get('TESTM_CONFIG_2'));
return $helper->generateForm([$form]);
}
/**
* Custom CSS & JavaScript Hook for FO
*/
public function hookHeader()
{
//$this->context->controller->addJS($this->_path.'/views/js/front.js');
if (Configuration::get('TESTM_CONFIG_2') == 1) {
$this->context->controller->addCSS($this->_path.'/views/css/'.((string)Configuration::get('TESTM_CONFIG_1')));
} else {
$this->context->controller->removeCSS($this->_path.'/views/css/'.((string)Configuration::get('TESTM_CONFIG_1')));
}
}
}
As you can see it's a pretty simple setting: just load a custom CSS file and choose if loading it or not. I've red official PS Docs per Multistore handling and searched online, but cannot find an answer to this specific problem.
I've also tried to add:
if (Shop::isFeatureActive()) {
$currentIdShop = Shop::getContextShopID();
Shop::setContext(Shop::CONTEXT_SHOP, $currentIdShop);
}
To the 'displayForm()' function, but without results.
Thank you in advance.
It seemsit was a caching error.
After trying many variations, I can confirm that the first solution I've tried was the correct one, meaning that:
if (Shop::isFeatureActive()) {
$currentIdShop = Shop::getContextShopID();
Shop::setContext(Shop::CONTEXT_SHOP, $currentIdShop);
}
needs to be added ad the beginning of the "displayForm()" function for it to work when selecting a single shop. Values are now correctly saved in the database. With a little bit extra logic it can be arranged to behave differently (if needed) when saving for "All shops" context.

Prestashop: How to filter in HelperList

Hello I try to filter a List in the Backoffice. It shows the filter, it also saves it after clicking on search, but nothing is happening. Same with pagination.
$schueler = $this->getAllSchuelerbyDiplom($id_diplom);
$diplom_name = $this->getDiplomNamebyID($id_diplom);
$fields_list = array(
'id_schueler' => array(
'title' => 'ID',
'align' => 'center',
'class' => 'fixed-width-xs',
'search' => true),
'customer_name' => array(
'title' => $this->l('ID Customer')),
'id_gruppe' => array(
'title' => $this->l('ID Gruppe')),
'name' => array(
'title' => $this->l('Name'),
'filter_key' => 'name'.$diplom_name),
'vorname' => array(
'title' => $this->l('Vorname')),
'punkte' => array(
'title' => $this->l('Punkte')),
'bestanden' => array(
'title' => $this->l('Bestanden'),
'active' => 'toggle',
'class' => 'fixed-width-xs',
'type' => 'bool'),
'date_added' => array(
'title' => $this->l('Datum'),
'class' => 'fixed-width-xs',
'type' => 'date'),
);
$helper = new HelperList();
$helper->table = 'no-idea-what-this-is-for';
$helper->title = $diplom_name;
$helper->shopLinkType = '';
$helper->actions = array('view', 'edit', 'delete');
$helper->listTotal = count($schueler);
$helper->identifier = 'id_schueler';
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name .'&diplom_name=' . $diplom_name;
return $helper->generateList($schueler, $fields_list);
What is wrong with my code? What is $helper->table for? I tried different things there, but nothing helps...
EDIT
public function getAllSchuelerbyDiplom($id_diplom) {
$query = new DbQuery();
$query->select('s.*, CONCAT(c.firstname,\' \',c.lastname) AS customer_name');
$query->from($this->table_name.'_schueler', 's');
$query->leftJoin('customer', 'c', 's.id_customer = c.id_customer');
$query->where('s.id_diplom = ' . (int)$id_diplom);
return Db::getInstance()->ExecuteS($query);
}
The problem is that HelperList object itself will only display filters being used but won't filter the actual data list for you.
In your $this->getAllSchuelerbyDiplom($id_diplom); method I assume you execute SQL query to retrieve all rows, however you need modify it to account for any filters, paginations (page number and rows per page) or ordering. You have to check GET/POST values or values set in cookie to detect them.
$helper->table sets the table name and list actions are prepended with that name so they are distinct from any other lists you might have on the page.
Edit:
Example of setting pagination and page
public function getPage()
{
// $tableName must be equal to what you set in $helper->table
// Check if page number was selected and return it
if (Tools::getIsset('submitFilter'.$tableName)) {
return (int)Tools::getValue('submitFilter'.$tableName);
}
else {
// Check if last selected page is stored in cookie and return it
if (isset($this->context->cookie->{'submitFilter'.$tableName})) {
return (int)$this->context->cookie->{'submitFilter'.$tableName};
}
else {
// Page was not set so we return 1
return 1;
}
}
}
public function getRowsPerPage()
{
// $tableName must be equal to what you set in $helper->table
// Check if number of rows was selected and return it
if (Tools::getIsset($tableName. '_pagination')) {
return (int)Tools::getValue($tableName. '_pagination');
}
else {
// Check if number of rows is stored in cookie and return it
if (isset($this->context->cookie->{$tableName. '_pagination'})) {
return (int)$this->context->cookie->{$tableName. '_pagination'};
}
else {
// Return 20 rows per page as default
return 20;
}
}
}
public function getAllSchuelerbyDiplom($id_diplom) {
$query = new DbQuery();
$query->select('s.*, CONCAT(c.firstname,\' \',c.lastname) AS customer_name');
$query->from($this->table_name.'_schueler', 's');
$query->leftJoin('customer', 'c', 's.id_customer = c.id_customer');
$query->where('s.id_diplom = ' . (int)$id_diplom);
// Limit the result based on page number and rows per page
$query->limit($this->getRowsPerPage(), ($this->getPage() - 1) * $this->getRowsPerPage());
return Db::getInstance()->ExecuteS($query);
}
You can place a p(Tools::getAllValues()); d($this->context->cookie->getAll(); after you generate a list then set a filter in your list and it will show you all the variables you need to create filters and ordering.

Creating a PDF document from a filtered CGridView - Yii

I am trying to create a PDF from a filtered CGridView. The value will be passed via dropdown in Advanced search but the problem is that i am unable to filter the search by my pdf function.
Controller
public function actionPrint() {
$mPDF1 = Yii::app()->ePdf->mpdf('ar','A4','14','dejavusanscondensed');
$model=new Country('search');
$model->center_id = 1;// This value will be passed from dropdown
//and i want the report to be made on this
$model->unsetAttributes();
if(isset($_GET['Country']))
$model->attributes=$_GET['Country'];
$html = '';
$html .= $this->renderPartial('candidates', array('model'=>$model, 'enablePagination' => false),true);
$mPDF1->WriteHTML($html, false);
$mPDF1->Output('list.pdf','D');
}
View
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'country-grid',
'dataProvider'=>$model->search($enablePagination),
'summaryText' => '',
// 'enablePagination' => false,
'filter'=>$model,
'columns'=>array(
'name',
array(
'header'=>' Total Registered Candidates',
'value'=>'$data->itemsTotal',
),
),
));
echo CHtml::link(
'Save as PDF',
Yii::app()->createUrl('country/print'),
array('class'=>'btnPrint btn btn-danger','target'=>'_blank'));
Model
public function search($enablePagination = true)
{
$criteria->together= true;
$criteria->with=array('center');
$criteria->compare('center.name', $this->center_id, true);
..........
if ($enablePagination)
{
$pagination = array(
'pageSize' => 30,
);
}
else
{
$pagination = false;
}
return new CActiveDataProvider($model, array(
'criteria' => $criteria,
'pagination' => $pagination,
));
}
Since center_id is a foreign key the line
$criteria->compare('center.name', $this->center_id, true);
should read
$criteria->compare('center_id', $this->center_id);
You could also do the following but this adds a condition on the joined table and could lead to slower queries.
$criteria->compare('center.id', $this->center_id);

How to pop up the msg box after deleting from cgridview?

This is the CButtonColumn of my gridview
array(
'header' => 'Action',
'class' => 'CButtonColumn',
'template' => '{view} {delete}',
'buttons' => array(
'delete' =>
array(
'url' => 'Yii::app()->controller->createUrl("/workorders/delete",array("id"=>$data->primaryKey))',
'label' => 'delete',
'options' => array( // this is the 'html' array but we specify the 'ajax' element
'confirm' => $alert,
'class' => 'grid_action_set1',
'ajax' => array(
'type' => 'POST',
'url' => "js:$(this).attr('href')", // ajax post will use 'url' specified above
'success' => 'function(data){
if(data == "true"){
//update the grid...
$.fn.yiiGridView.update("workorders-grid");
return false;
}else{
$("#mydialog").dialog("open"); return false;
return false;
}
}',
),
),
),
'view' => array
(
'label'=>'View workorder detail.',
'url'=>'Yii::app()->createUrl("/workorders/view", array("id"=>$data->id))',
),
),
'htmlOptions' => array('width' => '30px', 'style'=>'text-align:center;')
),
This is the check the record before delete
protected function beforeDelete()
{
if ($this->exists("(status_id = 6 OR status_id = 7) AND parent_mac = '$this->mac_address'"))
return false;
else
return parent::beforeSave(); // prevent actual DELETE query from being run
}
This is my controller
public function actionDelete($id)
{
if($this->loadModel($id)->delete())
{
if(!isset($_GET['ajax']))
Yii::app()->user->setFlash('success','Normal - Deleted Successfully');
else
echo "<div class='flash-success'>Ajax - Deleted Successfully</div>";
$data = 'true';
}else{
if(!isset($_GET['ajax']))
Yii::app()->user->setFlash('error','This node is a parents of some other node. <br/>Please replace.');
else
echo "<div class='flash-error'>This node is a parents of some other node. <br/>Please replace.</div>";
$data = 'false';
}
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
My problem is when the user click the delete button, the confirmation box "Are you sure to delete?" will come out. When user click "Yes", check the record is valid to delete.
If the record is valid to delete, delete the record and "successfully" Msg box pop up. update gridview.
If the record is not valid to delete, "the record is blah blah blah" Msg box pop up.
How can I do?
public function actionDelete($id) {
$jenis = Usaha::model()->findByAttributes(array('id_jenis' => $id));
if($jenis==''){
$this->loadModel($id)->delete();
}
else {
throw new CHttpException(400, "your message alert "); //try this , will show some alert this i used when some data connected with another table in database
}
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if (!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}

Yii: Multimodelform Extension - How to create more than 1 member

I'm using Multimodelform extension to create multiple model in a single form.
This extension is working great but unfortunately i would like more than 1 member instead.
I have tried it without success at all.
My problem is I could not make more than 1 member by this extension.
Here's my code :
From Controller
public function actionCreate()
{
Yii::import('ext.multimodelform.MultiModelForm');
$model=new Endheader;
$member = new Enddetail;
$member2 = new Enddetailnq; <-- i just ant to this new member.
$validatedMembers = array();
//$validatedMembers2 = array();
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Endheader']))
{
$model->attributes=$_POST['Endheader'];
if(isset($_POST['sav'])){
if((MultiModelForm::validate($member, $validatedMembers, $deleteItems) && MultiModelForm::validate($member2, $validatedMembers, $deleteItems)) && $model->save())
{
$masterValues = array('HEH_ID'=>$model->HEH_ID);
if(MultiModelForm::save($member,$validatedMembers,$deleteItems,$masterValues) && MultiModelForm::save($member2,$validatedMembers,$deleteItems,$masterValues))
$msg2 = CHtml::link('View Details',array('view','id'=>$model->HEH_ID));
// $this->redirect(array('view','id'=>$model->HCO_ID));
Yii::app()->user->setFlash('success','You data have been saved successfully. '.$msg2);
$this->redirect(array('update','id'=>$model->HEH_ID));
}
}
}
$this->render('create',array(
'model'=>$model,'transport'=>$transport,
'member2'=>$member2,
'member'=>$member,
// 'validatedMembers2' => $validatedMembers2,
'validatedMembers' => $validatedMembers,
));
}
From View
$memberFormConfig = array(
'elements'=>array(
'HED_RPASS'=>array(
'type'=>'text',
'maxlength'=>11,
),
'HED_PCS'=>array(
'type'=>'text',
'maxlength'=>5,
),
));
$this->widget('ext.multimodelform.MultiModelForm',array(
'id' => 'id_member', //the unique widget id
'formConfig' => $memberFormConfig, //the form configuration array
'model' => $member, //instance of the form model
'tableView' => true,
//if submitted not empty from the controller,
//the form will be rendered with validation errors
'validatedItems' => $validatedMembers,
//'sortAttribute' => 'position',
//array of member instances loaded from db
'data' => $member->findAll('HEH_ID=:HEH_ID', array(':HEH_ID'=>$model->HEH_ID)),
));
$memberFormConfig2 = array(
'elements'=>array(
'HED_ARV_PCS'=>array(
'type'=>'text',
'maxlength'=>5,
),
'HED_ARV_VOL'=>array(
'type'=>'text',
'maxlength'=>10,
),
));
$this->widget('ext.multimodelform.MultiModelForm',array(
'id' => 'id_member2', //the unique widget id
'formConfig' => $memberFormConfig2, //the form configuration array
'model' => $member2, //instance of the form model
'tableView' => true,
//if submitted not empty from the controller,
//the form will be rendered with validation errors
'validatedItems' => $validatedMembers,
//'sortAttribute' => 'position',
//array of member instances loaded from db
'data' => $member->findAll('HEH_ID=:HEH_ID', array(':HEH_ID'=>$model->HEH_ID)),
));