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;
}
Related
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;
}
}
}
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);
//}
The following function checks if the banner is old enough to make it inactive by setting the status field in the Banner table to 0.
/**
*
* Checks weather the banners are old enough to be turned back to non-premium
* and change the status to 0 , in case of non-premium
*
* #return void
*/
protected function check_status(){
$non_premium_expire = 5*24*60*60;
$premium_expire = 14*24*60*60;
$data = $this->Banner->find('all');
foreach ($data as $Banners) {
if ($Banners['Banner']['is_premium'] == 0) {
if ((time() - strtotime($Banners['Banner']['created'])) > $premium_expire) {
$this->Banner->id = $Banners['Banner']['id'];
$this->Banner->saveField('status',0);
}
else if ($Banners['Banner']['is_premium'] == 1) {
if ((time() - strtotime($Banners['Banner']['created'])) > $non_) {
$this->Banner->id = $Banners['Banner']['id'];
$this->Banner->saveField('status',0);
}
}
}
}
}
from mybanners() function. i.e. the check_status() function should be called when users open
/site-name/mybanners
I have called the check_status() function from mybanners() function shown below
public function mybanners()
{
$this->check_status();
$this->layout = 'index';
$this->loadModel('Banner');
$loggedUserId = $this->Auth->user('id');
My problem is that the one field status is not getting updated in the database even after trying set() and updateAll() function. Any solutions? I am newbie in cakephp
I figured it out. The working code is below.
**
*
* Checks weather the banners are old enough to be turned back to non-premium
* and change the status to 0 , in case of non-premium
*
* #return void
*/
protected function check_status(){
$non_premium_expire = 5*24*60*60;
$premium_expire = 14*24*60*60;
$data = $this->Banner->find('all');
//pr ($Banners);
//pr ((time() - strtotime($Banners['Banner']['modified'])) > 5*24*60*60);
//pr ((time() - strtotime($Banners['Banner']['modified'])) > 14*24*60*60);
//die();
foreach ($data as $Banners) {
if ($Banners['Banner']['is_premium'] == 0) {
if ((time() - strtotime($Banners['Banner']['modified'])) > $non_premium_expire) {
$id = $Banners['Banner']['id'];
//pr ("in non premium loop");
//pr ($id);
//die();
$data_one = array('id' => $id , 'status'=> 0, 'modified' => false);
$this->Banner->save($data_one);
//$this->Banner->clear();
}
}
if ($Banners['Banner']['is_premium'] == 1) {
if ((time() - strtotime($Banners['Banner']['modified'])) > $premium_expire) {
$id = $Banners['Banner']['id'];
//pr ("in premium loop");
//pr ($id);
//die();
$data_one = array('id' =>$id , 'status'=> 0, 'modified' => false);
//pr ($data_one);
//die();
$this->Banner->save($data_one);
//$this->Banner->clear();
}
}
}
}
Hi i am trying to use the TCPDF manual given in cakephp.
http://bakery.cakephp.org/articles/kalileo/2010/06/08/creating-pdf-files-with-cakephp-and-tcpdf
But its not at all working in my system. I followed the exact steps there...
Error:-
Class 'XTCPDF' not found
But there is a class name XTCPDF in my Vendor folder....
Any help plz ??
Thanks
you try change:
App::import('Vendor','xtcpdf');
to
App::import('Vendor','tcpdf/xtcpdf');
or maybe following this tutorial:
http://www.pedroventura.com/cakephp/crear-archivos-pdf-con-cakephp/
summary:
file: app/vendors/tcpdf/xtcpdf.php
<?php
App::import('Vendor','tcpdf/tcpdf');
class XTCPDF extends TCPDF
{
var $xheadertext = 'PDF creado using CakePHP y TCPDF';
var $xheadercolor = array(0,0,200);
var $xfootertext = 'Copyright © %d XXXXXXXXXXX. All rights reserved.';
var $xfooterfont = PDF_FONT_NAME_MAIN ;
var $xfooterfontsize = 8 ;
function Header()
{
list($r, $b, $g) = $this->xheadercolor;
$this->setY(10);
$this->SetFillColor($r, $b, $g);
$this->SetTextColor(0 , 0, 0);
$this->Cell(0,20, '', 0,1,'C', 1);
$this->Text(15,26,$this->xheadertext );
}
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');
}
}
?>
file: app/views/layouts/pdf.ctp
<?php
header("Content-type: application/pdf");
echo $content_for_layout;
?>
action in controller:
function descargar($id = null)
{
if (!$id)
{
$this->Session->setFlash('no has seleccionado ningun pdf.');
$this->redirect(array('action'=>'index'));
}
Configure::write('debug',0);
$resultado = $this->MiControlador->findById($id); // info from database
$this->set("datos_pdf",$resultado); // info to view (pdf)
$this->layout = 'pdf';
$this->render();
}
and
file: app/views/mi_aplicacion/descargar.ctp
<?php
App::import('Vendor','tcpdf/xtcpdf');
$tcpdf = new XTCPDF();
$textfont = 'freesans';
$tcpdf->SetAuthor("");
$tcpdf->SetAutoPageBreak( false );
$tcpdf->setHeaderFont(array($textfont,'',10));
$tcpdf->xheadercolor = array(255,255,255);
$tcpdf->xheadertext = 'Fecha: '. date('d-m-Y',time());
$tcpdf->xfootertext = 'www.example.cl';
$tcpdf->AddPage();
$tcpdf->SetTextColor(0, 0, 0);
$tcpdf->SetFont($textfont,'B',10);
$tcpdf->Cell(10,20,'Nombre:', 0, 0);
// more info
echo $tcpdf->Output('mi_archivo.pdf', 'D'); //D or I
?>
http://book.cakephp.org/2.0/en/core-utility-libraries/app.html#loading-vendor-files Here you will find, how do you load vendor in CakePHP 2.3.6...
I've started working on a theme from scratch, I've tried to replace the title of the textfield but when imploding the search variable into search_form, the result is blank. Any error that I could be missing?
`function mytheme_preprocess_search_block_form(&$form) {
$form['search'] = array();
$hidden = array();
// Provide variables named after form keys so themers can print each element independently.
foreach (element_children($form['form']) as $key) {
echo $key;
$type = $form['form'][$key]['#type'];
echo '__'.$type.'<br />';
if ($type == 'hidden' || $type == 'token') {
$hidden[] = drupal_render($form['form'][$key]);
}
else {
if($key == 'search_block_form')
{
$form['form'][$key]['#title'] = t('');
//$form['search'][$key] = drupal_render($form['form'][$key]);
}
else
{
$form['search'][$key] = drupal_render($form['form'][$key]);
}
}
}
// Hidden form elements have no value to themers. No need for separation.
$form['search']['hidden'] = implode($hidden);
// Collect all form elements to make it easier to print the whole form.
$form['search_form'] = implode($form['search']);
var_dump($form);
exit;
}`
Refer to http://drupal.org/node/1092122:
<?php
/**
* Implements hook_theme().
*/
function MYMODULE_theme($existing, $type, $theme, $path) {
return array(
'article_node_form' => array(
'render element' => 'form',
'template' => 'article-node-form',
// this will set to module/theme path by default:
'path' => drupal_get_path('module', 'MYMODULE'),
),
);
}
?>
<?php
/**
* Preprocessor for theme('article_node_form').
*/
function template_preprocess_article_node_form(&$variables) {
// nodeformcols is an alternative for this solution.
if (!module_exists('nodeformcols')) {
$variables['sidebar'] = array(); // Put taxonomy fields in sidebar.
$variables['sidebar'][] = $variables['form']['field_tags'];
hide($variables['form']['field_tags']);
// Extract the form buttons, and put them in independent variable.
$variables['buttons'] = $variables['form']['actions'];
hide($variables['form']['actions']);
}
}
?>
article-node-form.tpl.php
<?php echo drupal_render_children($form)?>