cakephp 2.1 and creating pdf - cakephp

hi all I'm trying to create an invoicing system however when i goto the related url i get a blank page and header just being the url. I've followed the following tutorial [http://bakery.cakephp.org/articles/kalileo/2010/06/08/creating-pdf-files-with-cakephp-and-tcpdf]
here is my viewPdf function in the invoices controller
function viewPdf($id = null)
{
if (!$id)
{
$this->Session->setFlash('Sorry, there was no property ID submitted.');
$this->redirect(array('action'=>'index_admin'), 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();
}
//End of Controller
}
and here is my viewPdf view
<?php
App::import('Vendor','xtcpdf');
$tcpdf = new XTCPDF();
$textfont = 'freesans'; // looks better, finer, and more condensed than 'dejavusans'
$fpdf->xheadertext = 'YOUR ORGANIZATION';
$tcpdf->SetAuthor("KBS Homes & Properties at http://kbs-properties.com");
$tcpdf->SetAutoPageBreak( false );
$tcpdf->setHeaderFont(array($textfont,'',40));
$tcpdf->xheadercolor = array(150,0,0);
$tcpdf->xheadertext = 'KBS Homes & Properties';
$tcpdf->xfootertext = 'Copyright © %d KBS Homes & Properties. All rights reserved.';
// add a page (required with recent versions of tcpdf)
$tcpdf->AddPage();
// 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
echo $tcpdf->Output('filename.pdf', 'D');
?>
to my knowledge it should be creating a pdf file that has the words 'hello world' written in it.
after following advice about that being outdated, I used the link to github and have this in my controller now
public function view($id = null) {
$this->set('title_for_layout', 'Invoices');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.png');
$this->layout='home_layout';
$this->Invoice->id = $id;
if (!$this->Invoice->exists()) {
throw new NotFoundException(__('Invalid invoice'));
}
$this->pdfConfig = array(
'orientation' => 'potrait',
'filename' => 'Invoice_' . $id
);
$this->set('invoice', $this->Invoice->read(null, $id));
}
}
and my view.ctp
<html>
<head></head>
<title></title>
<body>
<?php $this->pdfConfig = array('engine' => 'CakePdf.WkHtmlToPdf') ?>
<?php echo $invoice; ?>
</body>
</html>
it prints out Array but does not render it as a pdf file
here is a link to the github pagw
https://github.com/ceeram/CakePdf

Use this plugin, setup is on github page ;)
https://github.com/ceeram/CakePdf

this is an obsolete tutorial, this is a tutorial for Cakephp 1.2 and you are using 2.1.
It's much better the code from the link of GitHub that Matus Edko gave you.
By the way, is always better to show all the error and notifications when you are developing and testing, by setting up de "debug" to 3.
Configure::write('debug',3);

Related

testing cakephp restful api callback

I have followed the cakephp documentation for 2.0 to create a restFUL. I am not sure if I have it right.
If I was to just put the URL into the browser should I see the xml called back. I am just trying to test it but all I see is the standard view and not the xml view. I just want a quick test to see if I have it right.
The URL
http://www.mydomain.com/members/123.xml
The controller is Members and the method I am calling is view
Here is my code:
routes.php
Router::mapResources('members');
Router::parseExtensions('xml', 'json');
MembersController.php
public function view($id = null) {
if (!$this->Member->exists($id)) {
throw new NotFoundException(__('Invalid member'));
}
$options = array('conditions' => array('Member.' . $this->Member->primaryKey => $id));
$members = $this->Member->find('first', $options);
$this->set(array(
'member' => $members,
'_serialize' => array('member')
));
}
app/view/members/xml/view.ctp
echo $xml->serialize($member)
Have you the RequestHandler in your components array? If not put it in there.
See this page in the CakePHP book.
You don't need any view, CakePHP handles it automatically. Delete folder app/view/members/ with all files inside.

Json does not popup as download file in cakephp 2.3

I am using cakephp 2.3 and want to generate list of users in json format.
controller name: users
method: list
Earlier, I have done it in cake 1.3.x and when user tries access method via url in browser then output comes as download file but when i am doing it in cakephp 2.3 then it is showing me json output on browser page itself instead of download file.
here is my code:
Controller:
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public $helpers = array('Form', 'Html', 'Js', 'Time');
public $components = array('RequestHandler');
var $layout = 'js/default';
public function list() {
$this->log("i got data in user add:");
$this->log($this->request->data);
$posts['id']['name']='kapil';
$this->set(compact('posts'));
}
}
list.ctp file
<?php echo json_encode(compact('posts')); ?>
view/js/default.ctp
<?php echo $scripts_for_layout; ?>
<?php echo $this->fetch('content'); ?>
when i try to access my function in browser then i get this output
url: http://localhost/project/users/list
{"posts":{"id":{"name":"aditya"}}}
This output is correct but should come in download file format. I don't know what is wrong here.
If you are trying to force download, your code must make use of Response object.
Here is an example taken from CsvExport Behavior:
public function export() {
$this->autoRender = false;
$modelClass = $this->modelClass;
$this->response->type('Content-Type: text/csv');
$this->response->download( strtolower( Inflector::pluralize( $modelClass ) ) . '.csv' );
$this->response->body( $this->$modelClass->exportCSV() );
}
So your code would look like this :
public function list() {
$this->autoRender = false;
$this->log("i got data in user add:");
$this->log($this->request->data);
$posts['id']['name']='kapil';
$this->set(compact('posts'));
$modelClass = $this->modelClass;
$this->response->type('Content-Type: application/json');
$this->response->download('list.json');
}
Hope this helps!

select list association in cakephp

i am new to cake and using version 2.
i have models
hgcylinder.php
class HgCylinder extends AppModel {
//put your code here
var $name= "HgCylinder";
var $belongsTo = array('HgKeyGase');
}
hgkeygase.php
class HgKeyGase extends AppModel {
//put your code here
var $name= "HgKeyGase";
public $belongsTo = array(
'HgKeyColor' => array(
'className' => 'HgKeyColor',
'foreignKey' => 'hg_key_color_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
Controller HgCylindersController.php
<?php
class HgCylindersController extends AppController
{
var $name = "HgCylinders";
// var $scaffold;
function index()
{
$this->set('hey',$this->HgCylinder->find('all'));
}
public function edit($id = null) {
$this->HgCylinder->id = $id;
if ($this->request->is('post')) {
var_dump($this->request->data);
exit;
if ($this->HgCylinder->save($this->request->data)) {
$this->Session->setFlash(__('Cylinder has been updated successfull'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The cylinder could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->HgCylinder->read(null, $id);
}
$hg_key_gase_id = $this->HgCylinder->HgKeyGase->find('list');
$this->set(compact('hg_key_gase_id'));
}
}
?>
View : edit.ctp
<?php
echo $this->form->create('HgCylinder',array('action'=>'edit'));
echo $this->form->input('hg_key_gase_id',);
echo $this->form->input("capacityM3");
echo $this->form->input("weightEmpty");
echo $this->form->input("weightFilled");
echo $this->form->input("isFilled");
echo $this->form->end('Add');
?>
my problem is hg_key_gase_id is become select list with no options. if i changed the name to "hgKeyGas" in view and controller it shows the options from the hg_key_gases table. but on saving does not saving the value of hg_key_gase_id field in hg_cylinders table instead it stores null in this field.
second i want to know that it is necessary to have variable name passing to view from controller exactly same for as field in table.
try to stick to conventions.
so its
$hgKeyGases = $this->HgCylinder->HgKeyGase->find('list');
$this->set(compact('hgKeyGases'));
the pluralized form will be able to populate your select box (as documented in the cook book)
also use $this->Form->input() (note the capital F). $name is not necessary.
dont use read(), use find(first) instead. dont set the action (the form will post to itself by default).
and most importantly. ALWAYS respect the casing of files in your filesystem. especially if you plan on deploying on NIX systems (which are case sensitive).
so it would be HgCylinder.php and HgKeyGase.php as Model class files.
last tip: use baking (cake bake via shell console) to bake your crud files. this way you learn how its done the right way. it would have also answered your question itself by the way.
the documentation can be found here: http://book.cakephp.org/2.0/en/index.html
maybe you found an old outdated version, the 2.x one is the one you should have used.

Set page title when handling errors in CakePHP

I need to change page title from default "Error" when handling errors like 404. So I need to put my the title in the variable $title_for_layout for my Layout. I tried to create custom error handling function by changing configuration in app/Config/core.php and setting the page title as in controllers
Configure::write('Error.handler', function($code, $description, $file = null, $line = null, $context = null) {
$this->set('title_for_layout', 'Vyskytla sa chyba');
});
As I expected, I got a PHP error (line 59 is the second line in the code sample)
Fatal error: Using $this when not in object context in /var/www/web/app/Config/core.php on line 59
So how I can set the title for my default.ctp layout?
Thanks.
In CakePHP 2.0, you can try the following code to achieve the same you needed.
Try this:
/app/Config/core.php
Exception render need to set as an AppExceptionRender. Example:
Configure::write('Exception', array(
'handler' => 'ErrorHandler::handleException',
'renderer' => 'AppExceptionRenderer',
'log' => true
));
/app/Controller/ErrorsController.php
class ErrorsController extends AppController {
public $name = 'Errors';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('error404');
}
public function error404() {
//$this->layout = 'default';
$this->set('title_for_layout', 'Vyskytla sa chyba');
}
}
/app/Lib/Error/AppExceptionRenderer.php
App::uses('ExceptionRenderer', 'Error');
class AppExceptionRenderer extends ExceptionRenderer {
public function notFound($error) {
$this->controller->redirect(array('controller' => 'errors', 'action' => 'error404'));
}
}
/app/View/Errors/error404.ctp
<div class="inner404">
<h2>404 Error - Page Not Found</h2>
</div>
Insert it where you need: throw new NotFoundException();
Ref: CakePHP 2.0 - How to make custom error pages?
For < CakePHP 2.x:
If you create a custome error page view in app/views/errors then in a
php section on that error view page you can use:
$this->setLayout("Title for the error page here");
Then when you see the error page, it will have your title. Again, that
is if you set a custom error page.
Here is another way to do the same you needed.
// Create an error.php file in your /app folder with the following code:
<?php
class AppError extends ErrorHandler {
function error404($params) {
$this->controller->layout = "error";
$this->set('title_for_layout', 'Vyskytla sa chyba');
parent::error404($params);
}
}
?>

How to use tinymce plugin?

I have tried many times to use this plugin and I failed.
I am following documentation, but it does not work for me.
I am posting the simple code here, to know what wrong I am doing.
1-I put this plugin in this folder app/plugins
2- I add TinyMce helper to articles_controller
<?php
class ArticlesController extends AppController {
// good practice to include the name variable
var $name = 'articles';
// load any helpers used in the views
var $helpers = array('Html', 'Form','TinyMce.TinyMce');
/**
* index()
* main index page of the formats page
* url: /formats/index
*/
function index(){
// get all formats from database where status = 1
$articles = $this->Article->find("all") ;
$this->set('articles', $articles);
}
function admin_add() {
// if the form data is not empty
if (!empty($this->data)) {
// initialise the format model
$this->Article->save($this->data);
// set a flash message
$this->Session->setFlash('The Format has been saved');
// redirect
$this->redirect(array('action'=>'index'));
} else {
// set a flash message
$this->Session->setFlash('The Format could not be saved. Please, try again.','default', array('class' => 'flash_bad'));
}
}
}
?>
3- in the view file articles/admin_add.ctp I added the editor
// i think the problem in this code
<?php $this->TinyMce->editor(array(
'theme' => 'advanced'
)); ?>
<div class="formats form">
<?php echo $form->create('Article');?>
<fieldset>
<legend>Add a article</legend>
<?php
// create the form inputs
echo $this->Form->input('title');
echo $this->Form->input('content'); ?>
</fieldset>
<?php echo $form->end('Add');?>
</div>
<ul class="actions">
<li><?php echo $html->link('List Articles', array('action'=>'index'));?></li>
</ul>
You need to put tinymce files into your js assets
Then you have to add into section of your layout.
Then you'll need to init tinymce according to example provided on tinymce website (ex: full tinymce layout) and configure it according to your requirements.
I'd personally would not rely on such cake plugins, when actions required to get things working are not many and they are simple enough.

Resources