CakePHP Custom Query Paginator - cakephp

Currently I am got 2 page require Pagination.
I also do some research such as setting or at model do the custom Query. However the Paginator can't work.
Now I am trying add custom query paginator to index page. (I need to use group by)
I also trying to add custom query paginator to view page. ( I need base on the id)
Controller:
public function index() {
$setting = $this->Paginator->settings = $this->Report->query('
SELECT SUM( seats_occupied ) as totalOccupied, event_date, r.event_date_id
FROM reports r, event_dates ed WHERE r.event_date_id = ed.event_date_id
GROUP BY event_date
');
debug($this->Paginator->paginate());
$this->set('showDate',$setting);
}
public function view($eventDateId = null){
if (!$eventDateId) {
throw new NotFoundException(__('Invalid post'));
}
// We only want single post so we use FindById.
$post = $this->Report->findAllByEventDateId($eventDateId);
// debug($this->Paginator->paginate($post));
if (!$post) {
//if user requet fypcakephp/view without id will throw the not found except
throw new NotFoundException(__('Invalid post'));
}
$setting = $this->Paginator->settings = $this->Report->query("
SELECT *
FROM reports where event_date_id='$eventDateId' order by period asc
");
//array( 'conditions' => array( 'event_date_id' => $post));
debug($setting);
$this->set('viewData', $setting); //Then send this data
}
I also got try do at model custom Query however If I do this way , my view can't get the data I want due to I using "Group By".
//To custom the paginate display the thing you want. (This one return)
//public function paginate($conditions, $fields, $order, $limit, $page = 1,
// $recursive = null, $extra = array())
//{
// $recursive = 0;
//
// // Mandatory to have
// $this->useTable = false;
// $sql = '';
//
//
// $sql .= " select * from reports;";
//
//
//
// $sql .= " SELECT SUM( seats_occupied ) as totalOccupied, event_date,r.event_date_id
// FROM reports r, event_dates ed WHERE r.event_date_id = ed.event_date_id
// GROUP BY event_date; ";
//
//
//
// // Adding LIMIT Clause
//// $sql .= (($page - 1) * $limit) . ', ' . $limit;
//
// $results = $this->query($sql);
//
// return $results;
//}
//public function paginateCount($conditions = null, $recursive = 0, $extra = array())
//{
// $sql = '';
//
// $sql .= "SELECT SUM( seats_occupied ) as totalOccupied, event_date ,r.event_date_id
// FROM reports r, event_dates ed WHERE r.event_date_id = ed.event_date_id
// GROUP BY event_date";
//
// $this->recursive = $recursive;
//
// $results = $this->query($sql);
//
// return count($results);
//}

Related

How to retain search string when using pagination in cakephp 4?

I am using cakePHP 4 and I want to paginate my search query. I have users index page and when I search something whose resultant data exceed the defined limit of showing data. Whenever I search something I want the search string to retain in the input box even if I jump to the next page
public function index(){
$this->conditions = array();
if($this->session->check('conditions')){
$this->conditions = $this->session->read('conditions');
}
if ($this->request->is('post')) {
$data = $this->request->getData();
if(!empty($data['search_string'])){
$searchString = trim($data['search_string']);
if($data['search_by'] == 1){
$conditions = array('Users.id LIKE '=> $searchString);
}elseif($data['search_by'] == 2){
$conditions = array('Users.username LIKE '=>'%'.$searchString.'%');
}elseif($data['search_by'] == 3){
$conditions = array('Groups.name LIKE ' => '%'.$searchString.'%');
}
}
$this->conditions = array ($conditions);
$this->session->write('conditions',$this->conditions);
$this->paginate['conditions'] = $this->conditions;
$this->paginate['contain'] = ['Userdetails','Groups'];
$this->paginate['limit'] = 8;
$users = $this->paginate($this->Users);
$this->set('users',$users);
}else{
$this->session->write('conditions',$this->conditions);
$this->paginate['conditions'] = $this->conditions;
$this->paginate['contain'] = ['Userdetails','Groups'];
$this->paginate['limit'] = 8;
$users = $this->paginate($this->Users);
$this->set('users',$users);
}
}

Codeigniter 3.1.9 - CI_Session is filling up my database on every refresh

I have been getting back into Codeigniter as support was picked up by BCIT. I have a problem with ci_sessions and the database driver which is regenerating the encrypted session ID and storing new data in my database on every page refresh. I'm so frustrated right now! I have both secure file storage and database for both common drivers. I want to use both or either but the effect on my application is the same whether I am using a database or files. The ci_session keeps refreshing and it is not ideal for logins, registration or any account type. Please help me see what I am doing wrong? Much appreciation granted in advance.
Config:
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'users';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
Controllers:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* User Management class created by CodexWorld
*/
class Limousers extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('user');
}
/*
* User account information
*/
public function account(){
print_r($_SESSION);
$data = array();
print_r($this->session->userdata());
if($this->session->userdata('isUserLoggedIn')){
$data['user'] = $this->user->getRows(array('id'=>$this->session->userdata('userId')));
//load the view
$this->load->view('limousers/account', $data);
}else{
redirect('limousers/login');
exit;
}
}
/*
* User login
*/
public function login(){
print_r($_SESSION);
if($this->session->userdata('isUserLoggedIn'))
{
print_r($this->session->userdata);
redirect('limousers/account');
exit;
}
$data = array();
if($this->session->userdata('success_msg')){
$data['success_msg'] = $this->session->userdata('success_msg');
$this->session->unset_userdata('success_msg');
}
if($this->session->userdata('error_msg')){
$data['error_msg'] = $this->session->userdata('error_msg');
$this->session->unset_userdata('error_msg');
}
if($this->input->post('loginSubmit')){
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
if ($this->form_validation->run() == true) {
$con['returnType'] = 'single';
$con['conditions'] = array(
'email'=>$this->input->post('email'),
'password' => md5($this->input->post('password')),
'status' => '1'
);
$checkLogin = $this->user->getRows($con);
if($checkLogin){
$this->session->set_userdata('name',$con['conditions']['email']);
$this->session->set_userdata('isUserLoggedIn',TRUE);
$this->session->set_userdata('userId',$checkLogin['id']);
redirect('limousers/account');
exit;
}else{
$data['error_msg'] = 'Wrong email or password, please try again.';
}
}
}
//load the view
$this->load->view('limousers/login', $data);
}
/*
* User registration
*/
public function registration(){
print_r($_SESSION);
$data = array();
$userData = array();
if($this->input->post('regisSubmit')){
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_email_check');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_rules('conf_password', 'confirm password', 'required|matches[password]');
$userData = array(
'name' => strip_tags($this->input->post('name')),
'email' => strip_tags($this->input->post('email')),
'password' => md5($this->input->post('password')),
'gender' => $this->input->post('gender'),
'phone' => strip_tags($this->input->post('phone'))
);
if($this->form_validation->run() == true){
$insert = $this->user->insert($userData);
if($insert){
$this->session->set_userdata('success_msg', 'Your registration was successfully. Please login to your account.');
redirect('limousers/login');
exit;
}else{
$data['error_msg'] = 'Some problems occured, please try again.';
}
}
}
$data['user'] = $userData;
//load the view
$this->load->view('limousers/registration', $data);
}
/*
* User logout
*/
public function logout(){
$this->session->unset_userdata('isUserLoggedIn');
$this->session->unset_userdata('userId');
$this->session->sess_destroy();
redirect('limousers/login');
exit;
}
/*
* Existing email check during validation
*/
public function email_check($str){
$con['returnType'] = 'count';
$con['conditions'] = array('email'=>$str);
$checkEmail = $this->user->getRows($con);
if($checkEmail > 0){
$this->form_validation->set_message('email_check', 'The given email already exists.');
return FALSE;
} else {
return TRUE;
}
}
}
Models:
<?php if ( ! defined('BASEPATH')) exit('No direct script access
allowed');
class User extends CI_Model{
function __construct() {
$this->userTbl = 'users';
}
/*
* get rows from the users table
*/
function getRows($params = array()){
$this->db->select('*');
$this->db->from($this->userTbl);
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
$this->db->where($key,$value);
}
}
if(array_key_exists("id",$params)){
$this->db->where('id',$params['id']);
$query = $this->db->get();
$result = $query->row_array();
}else{
//set start and limit
if(array_key_exists("start",$params) &&
array_key_exists("limit",$params)){
$this->db->limit($params['limit'],$params['start']);
}elseif(!array_key_exists("start",$params) &&
array_key_exists("limit",$params)){
$this->db->limit($params['limit']);
}
$query = $this->db->get();
if(array_key_exists("returnType",$params) &&
$params['returnType'] == 'count'){
$result = $query->num_rows();
}elseif(array_key_exists("returnType",$params) &&
$params['returnType'] == 'single'){
$result = ($query->num_rows() > 0)?$query- >row_array():FALSE;
}else{
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
}
}
//return fetched data
return $result;
}
/*
* Insert user information
*/
public function insert($data = array()) {
//add created and modified data if not included
if(!array_key_exists("created", $data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists("modified", $data)){
$data['modified'] = date("Y-m-d H:i:s");
}
//insert user data to users table
$insert = $this->db->insert($this->userTbl, $data);
//return the status
if($insert){
return $this->db->insert_id();
}else{
return false;
}
}
}

Cakephp save data and read MAX

I'm trying to save data in CakePHP in this way:
get max entry_id from table translations
(SELECT MAX(entry_id) as res FROM translations) + 1
save data into translations table
$translationData = array('entry_id' => $entry_id, 'language_id' => $key, 'text' => $item);
$translation = new Translation();
$translation->set($translationData);
$translation->save();
again get max entry_id
save next set of data
again get max entry_id
save next set of data
Please have a look at my code:
$this->request->data['Product']['name_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['name']);
$this->request->data['Product']['description_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['description']);
$this->request->data['Product']['seo_title_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_title']);
$this->request->data['Product']['seo_keywords_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_keywords']);
$this->request->data['Product']['seo_desc_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_desc']);
saveTranslations method:
public function saveTranslations($data) {
$entry_id = $this->getNextFreeId();
foreach($data as $key => $item) {
if($item != "") {
$this->create();
$temp['Translation']['entry_id'] = $entry_id;
$temp['Translation']['language_id'] = $key;
$temp['Translation']['text'] = $item;
$this->save($temp);
}
}
return $entry_id;
}
getNextFreeId method:
public function getNextFreeId() {
$result = $this->query("SELECT MAX(entry_id) as res FROM translations");
return $result[0][0]['res'] + 1;
}
I don't know why entry_id have all the time the same value.
After many hours of searching for solution I finally managed to solve the problem in very easy way - just add false parameter in query method:
$this->query("INSERT INTO translations(entry_id, language_id, text) VALUES($entry_id, $key, '$item')", false);
and
$result = $this->query("SELECT SQL_CACHE MAX(entry_id) as res FROM translations", false);

How do you filter Joomla 3 articles by article id

I'm trying to create a Joomla module that displays articles based on categories and tags.
I've taken code for selecting tagged articles from https://github.com/lasinducharith/joomla-tags-selected) and introduced it into a copy of mod_articles_news:
public static function getList(&$params)
{
$app = JFactory::getApplication();
$db = JFactory::getDbo();
// Code base on https://github.com/lasinducharith/joomla-tags-selected to fetch ids of tagged articles
$tagsHelper = new JHelperTags;
$tagIds = $params->get('tagid', array());
$tagIds = implode(',', $tagIds);
echo '<pre>search for tags[' . $tagIds . ']';
$query=$tagsHelper->getTagItemsQuery($tagIds, $typesr = null, $includeChildren = false, $orderByOption = 'c.core_title', $orderDir = 'ASC',$anyOrAll = true, $languageFilter = 'all', $stateFilter = '0,1');
$db->setQuery($query, 0, $maximum);
$results = $db->loadObjectList();
$article_ids=array();
foreach ($results as $result){
$article_ids[]=$result->content_item_id;
}
echo ' yields articles[' . implode(',', $article_ids ) . ']</pre>';
// Get an instance of the generic articles model
$model = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$appParams = JFactory::getApplication()->getParams();
$model->setState('params', $appParams);
// Set the filters based on the module params
$model->setState('list.start', 0);
$model->setState('list.limit', (int) $params->get('count', 15));
$model->setState('filter.published', 1);
$model->setState('list.select', 'a.fulltext, a.id, a.title, a.alias, a.introtext, a.state, a.catid, a.created, a.created_by, a.created_by_alias,' .
' a.modified, a.modified_by, a.publish_up, a.publish_down, a.images, a.urls, a.attribs, a.metadata, a.metakey, a.metadesc, a.access,' .
' a.hits, a.featured' );
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$model->setState('filter.access', $access);
// Category filter
$model->setState('filter.category_id', $params->get('catid', array()));
// Article filter
$model->setState('filter.id', $article_ids);
// Filter by language
$model->setState('filter.language', $app->getLanguageFilter());
// Set ordering
$ordering = $params->get('ordering', 'a.publish_up');
$model->setState('list.ordering', $ordering);
if (trim($ordering) == 'rand()')
{
$model->setState('list.direction', '');
}
else
{
$direction = $params->get('direction', 1) ? 'DESC' : 'ASC';
$model->setState('list.direction', $direction);
}
// Retrieve Content
$items = $model->getItems();
$newitems=array();
foreach ($items as &$item)
{
echo '<pre>fetched article[' . $item->id .'] which is ';
if ( !in_array($item->id, $article_ids )){
echo 'not tagged';
} else{
echo 'tagged';
}
echo '</pre>';
...
}
return $newitems;
}
The debug statements give me:
search for tags[2] yields articles[40,44,45]
fetched article[45] which is tagged
fetched article[44] which is tagged
fetched article[43] which is not tagged
fetched article[42] which is not tagged
fetched article[41] which is not tagged
fetched article[40] which is tagged
fetched article[39] which is not tagged
fetched article[38] which is not tagged
So the articles have not been filtered by id. I'd be very grateful for any advice.
Thanks
Found the problem, the filter should be article_id:
// Article filter
$model->setState('filter.article_id', $article_ids);
Now it selects articles based on tags and categories

CakePHP 2.2 - TCPDF - invalid property message

I have a problem with TCPDF:
viewPDF:
function viewPdf($id = null)
{
if (!$id)
{
$this->Session->setFlash('Sorry, there was no property ID submitted.');
$this->redirect(array('action'=>'index'), null, true);
}
Configure::write('debug',0); // Otherwise we cannot use this method while developing
$id = intval($id);
$property = $this->__view($id); // here the data is pulled from the database and set for the view
if (empty($property))
{
$this->Session->setFlash('Sorry, there is no property with the submitted ID.');
$this->redirect(array('action'=>'index'), null, true);
}
$this->layout = 'pdf'; //this will use the pdf.ctp layout
$this->render();
}
__view:
function __view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Calculation.', true));
$this->redirect(array('action'=>'index'));
}
$this->set('calculation', $this->Calculation->read(null, $id));
}
viewPDF.ctp:
<?php
App::import('Vendor','xtcpdf');
$tcpdf = new XTCPDF();
$textfont = 'freesans'; // looks better, finer, and more condensed
than 'dejavusans'
$tcpdf->SetAuthor("KBS Homes & Properties a http://kbs-properties.com");
$tcpdf->SetAutoPageBreak( false );
$tcpdf->setHeaderFont(array($textfont,'',20));
$tcpdf->xheadercolor = array(150,0,0);
$tcpdf->xheadertext = 'Test';
$tcpdf->xfootertext = 'Copyright © %d KBS Homes & Properties. All
rights reserved.';
// Now you position and print your page content
// example:
$tcpdf->SetTextColor(0, 0, 0);
$tcpdf->SetFont($textfont,'B',20);
$tcpdf->Cell(0,14, "Hello World", 0,1,'L');
// ...
// etc.
// see the TCPDF examples
$tcpdf->Output('filename.pdf', 'I');
?>
PDF layout for CakePHP 2.2 ($content_for_layout is depricated):
<?php
header("Content-type: application/pdf");
echo $this->fetch('content');
?>
xtcpdf.php in app/Vendor:
<?php
App::import('Vendor','tcpdf/tcpdf');
class XTCPDF extends TCPDF
{
var $xheadertext = 'PDF created using CakePHP and TCPDF';
var $xheadercolor = array(0,0,200);
var $xfootertext = 'Copyright © %d XXXXXXXXXXX. All rights reserved.';
var $xfooterfont = PDF_FONT_NAME_MAIN ;
var $xfooterfontsize = 8 ;
/**
* Overwrites the default header
* set the text in the view using
* $fpdf->xheadertext = 'YOUR ORGANIZATION';
* set the fill color in the view using
* $fpdf->xheadercolor = array(0,0,100); (r, g, b)
* set the font in the view using
* $fpdf->setHeaderFont(array('YourFont','',fontsize));
*/
function Header()
{
list($r, $b, $g) = $this->xheadercolor;
$this->setY(10); // shouldn't be needed due to page margin, but helas, otherwise it's at the page top
$this->SetFillColor($r, $b, $g);
$this->SetTextColor(0 , 0, 0);
$this->Cell(0,20, '', 0,1,'C', 1);
$this->Text(15,26,$this->xheadertext );
}
/**
* Overwrites the default footer
* set the text in the view using
* $fpdf->xfootertext = 'Copyright © %d YOUR ORGANIZATION. All rights reserved.';
*/
function Footer()
{
$year = date('Y');
$footertext = sprintf($this->xfootertext, $year);
$this->SetY(-20);
$this->SetTextColor(0, 0, 0);
$this->SetFont($this->xfooterfont,'',$this->xfooterfontsize);
$this->Cell(0,8, $footertext,'T',1,'C');
}
}
?>
And I always get "Sorry, there is no property with the submitted ID." and I don't see the problem.
you should have a look on this code :
function __view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Calculation.', true));
$this->redirect(array('action'=>'index'));
}
$data = $this->Calculation->read(null, $id));
return $data;
}

Resources