how to use cakephp dompdf for a print all function - cakephp

I'm already using dompdf to generate a pdf for each single view of my project using view_pdf function explained in cake tutorial
public function view_pdf($id = null) {
$this->Stock->id = $id;
if (!$this->Stock->exists()) {
throw new NotFoundException(__('Invalid stock'));
}
// increase memory limit in PHP
ini_set('memory_limit', '512M');
$this->set('stock', $this->Stock->read(null, $id));
}
Now I need to have a "print all" button which have to make a pdf file contain whole views.
Could I use view_pdf function in a "for each" loop? And could I make a file for this specific pdf instead a view?
I'm quite new on CakePhp so it's very appreciated a code example.
Thanks !!!

Related

Trying to write a simple Joomla plugin

Please help, this is my first plugin I'm writing and I'm completely lost. I'm trying to write and update information in a table in a joomla database using my custom giveBadge() function. The functions receives two different variables, the first variable is the $userID and the second one is the digit 300 which I pass at the bottom of the class using giveBadge(300). At the same comparing the $userID in the Joomla database to ensure that the number 300 is given to the current user logged in the Joomla site.
Thanks in advance.
<?php
defined('JPATH_BASE') or die;
class plgUserBadge extends JPlugin
{
public function onUserLogin () {
$user =& JFactory::getUser();
$userID =& user->userID;
return $userID;
}
public function giveBadge ($userID, &$badgeID) {
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Fields to update.
$fields = array(
'profile_value=\'Updating custom message for user 1001.\'',
'ordering=2');
// Conditions for which records should be updated.
$conditions = array(
'user_id='.$userID,
'profile_key=\'custom.message\'');
$query->update($db->quoteName('#__user_badges'))->set($fields)->where($conditions);
$db->setQuery($query);
try {
$result = $db->query();
} catch (Exception $e) {
// Catch the error.
}es = array(1001, $db->quote('custom.message'), $db->quote('Inserting a record using insert()'), 1);
}
}
giveBadge(300); //attaches to $badgeID
?>
Here is not going well with your code:
You can drop the assign by reference in all your code (&) - you really don't need it, in 99% of the cases.
Use an IDE (for example Eclipse with PDT). At the top of your code you have & user->userID; Any IDE will spot your error and also other things in your code.
Study existing plugins to understand how they work. Here is also the documentation on plugins.
The method onUserLogin() will automatically be called by Joomla when the specific event is triggered (when your plugin is activated). Check with a die("My plugin was called") to see if your plugin is really called
inside onUserLogin() you do all your business logic. You are not supposed to return something, just return true. Right now your method does absolutely nothing. But you can call $this->giveBadge() to move the logic to another method.

CakePHP 2 : Implement CakePDF plugin by Ceeram

I'm trying to implement the CakePDF plugin designed by Ceeram.
I'm using CakePHP 2 and I work locally using wamp on windows vista. I followed everything from the readme file but I got stucked at some point.
What I'd firstly like to do is converting an HTML link to a PDF using the WkHtmlToPdf engine. I see many people having issues to make it work so I'm gonna detail all the way through in the following different steps.
STEP 1: CakePdf plugin by Ceeram
I downloaded the plugin at https://github.com/ceeram/CakePdf
I extracted the contained folder into app/Plugin/CakePdf
STEP 2: Bootstrap
I added the following lines - app/Config/bootstrap.php :
CakePlugin::load('CakePdf', array('bootstrap' => true, 'routes' => true));
Configure::write('CakePdf', array(
'engine' => 'CakePdf.WkHtmlToPdf'
),
'orientation' => 'portrait',
'download' => true
));
STEP 3: Controller
I've created my controller "InvoicesController.php" - app/Controller/InvoicesController.php:
class InvoicesController extends AppController {
public $components = array('RequestHandler');
public function view($id = null) {
$this->Invoice->id = $id;
if (!$this->Invoice->exists()) {
throw new NotFoundException(__('Invalid invoice'));
}
$this->pdfConfig = array(
'orientation' => 'portrait',
'filename' => 'Invoice_' . $id
);
$this->set('invoice', $this->Invoice->read(null, $id));
}
}
STEP 4: View
I've created a pdf folder in my view folder and created view.ctp in app/View/Invoices/pdf/view.ctp.
STEP 5: Layout
I've created a pdf folder in my layout folder and created app/View/Layouts/pdf/default.ctp
That's about it. In my view I couldn't make a PDF file from an URL.
Although I have to mention I'm new in OOP and CakePHP so I would be very grateful if you could show me how to have this done. I'm sure it will help others because there many newbies like me who want to do this but because it's all meant for advanced programmers we cannot figure out how to put the pieces together.
Thank you very much for your understanding and your help!
[THIS POST IS MODIFIED EACH TIME THERE IS A NEW ANSWER WHICH IMPROVES IT]
You need to add RequestHandler component, and browse to localhost/invoices/view/1.pdf
Looks like i had forgotten to mention to add RequestHandler component in the readme.
Also for WkHtmlToPdf you need to tell it where it can find it, and since you are on windows the default location surely wont work for you. You can set the location with Configure::write('CakePdf.binary', 'C:\Program Files\wkhtmltopdf\wkhtmltopdf.exe') after having installed it on windows
You are missing this code in app/config/routers.php
Router::parseExtensions();
Router::setExtensions(array('json', 'xml', 'rss', 'pdf'));
details available on:
http://www.dereuromark.de/2014/04/08/generating-pdfs-with-cakephp/

Styling/Theming Drupal 7 Content Type Record

I developed a Content type of "Car Sales" with following fields:
Manufacturer
Model
Make
Fuel Type
Transmission (Manual/Automatic)
Color
Registered? (Yes/No)
Mileage
Engine Power
Condition (New/Reconditioned/Used)
Price
Pictures (Multiple uploads)
I have developed View of this Content Type to display list of cars. Now I want to develop a screen/view for individual Car Sale Record like this:
Apart from arranging fields, please note that I want to embed a Picture Gallery in between. Can this be achieved through Drupal 7 Admin UI or do I need to create custom CSS and template files? If I need to edit certain template files/css, what are those? I'm using Zen Sub Theme.
I would accomplish this by creating a page, and then creating a node template to accompany it. Start by creating a new node, and then record the NID for the name of the template.
Then, in your template, create a new file, and name it in the following manner: node--[node id].tpl.php
Then, in that file, paste in the following helper function (or you can put it in template.php if you're going to use it elsewhere in your site):
/**
* Gets the resulting output of a view as an array of rows,
* each containing the rendered fields of the view
*/
function views_get_rendered_fields($name, $display_id = NULL) {
$args = func_get_args();
array_shift($args); // remove $name
if (count($args)) {
array_shift($args); // remove $display_id
}
$view = views_get_view($name);
if (is_object($view)) {
if (is_array($args)) {
$view->set_arguments($args);
}
if (is_string($display_id)) {
$view->set_display($display_id);
}
else {
$view->init_display();
}
$view->pre_execute();
$view->execute();
$view->render();
//dd($view->style_plugin);
return $view->style_plugin->rendered_fields;
} else {
return array();
}
}
Then add the following code to your template:
<?php
$cars = views_get_rendered_fields('view name', 'default', [...any arguments to be passed to the view]);
foreach ($cars as $car): ?>
<div>Put your mockup in here. It might be helpful to run <?php die('<pre>'.print_r($car, 1).'</pre>'); ?> to see what the $car array looks like.</div>
<?php endforeach;
?>
Just change the placeholders in the code to whatever you want the markup to be, and you should be set!
As I mentioned above, it's always helpful to do <?php die('<pre>'.print_r($car,1).'</pre>'); ?> to have a visual representation of what the array looks like printed.
I use views_get_rendered_fields all the time in my code because it allows me to completely customize the output of the view.
As a Reminder: Always clear your caches every time you create a new template.
Best of luck!

CakePHP generate and save PDF

I am using CakePHP for an application that does auto generation of vouchers to a PDF file. But they work through user clicks. Now I wish to create it automatically and have the file written to the server hard disk. Then later on, these files will get zipped up and sent to an email of my choice.
For the PDFs I use Html2ps/Html2pdf component found in CakePHP. You can view it here http://bakery.cakephp.org/articles/Casmo/2010/06/26/creating-pdf-files-with-html2ps-html2pdf
One issue I have is the formatting doesn't look right. If I have links that look like this:
http://www.mydomain.com/this-is-my-perma-link
They will render this way in the generated PDF:
http://www.mydomain.com/this- is- my- perma- link
And that would be a broken link. I've tried to use other characters to replace the dash but it doesn't work. I am not sure why.
Another issue is, how can I write the generated PDF file to my server hard disk? Is there an option for me to do that and how do I define the destination. Any examples?
Maybe thanks in advance!
Hi you can to use FPDF library . and you can to save file in the server and then redirect to other function.
check the next code.
///Call to library
<?php
App::uses('AppController', 'Controller');
require_once APP . 'Vendor' . DS . 'fpdf17' . DS . 'fpdf.php';
class TestController extends AppController {
public function test(){
--Create fpdf.
$pdf = new FPDF();
$pdf->AddPage();
$pdf->Output('files/Report.pdf');
$pdf->text($x,$y,'Txt');
return $this->redirect(
array('controller' => 'Test', 'action' => 'test_new')
);
}
}

How to reduce form code duplication in CakePHP

I have a form in CakePHP with a few dozen fields in it. From all the examples I have seen, there is duplicate form code for an add view and an edit view.
Is there any tricks to keep the duplication out? What is best method in CakePHP for this?
What I do, is to put all form fields in an element, and then insert the element in the add.ctp and edit.ctp
Don't forget to add the hidden field with the id in the edit.ctp
This way all visible elements are in one file, easier to maintain.
View/MyModel/add.ctp
echo $this->Form->create('MyModel');
echo $this->element('my_form');
echo $this->Form->end();
View/MyModel/edit.ctp
echo $this->Form->create('MyModel');
echo $this->Form->input('id');
echo $this->element('my_form');
echo $this->Form->end();
View/Elements/my_form.ctp
// your form inputs
// whatever they are
You should NOT merge those views, because add/edit are different actions and deserve separate view files. As your application grows you will realize that its good to have separate views to reduce complexity of if else conditions.
If you still want to avoid the separate files, Use
function add() {
.....
$this->render('edit')
}
I've done this before, but reverted back to having separate views, mainly for my own sanity.
It's easy enough to do. The edit requires an input for the record id. This is usually hidden. Any default form values for the add form will have to be contained in conditionals so that the stored values are not overwritten with defaults when you are editing a record
On the controller side of things, you'll need a conditional statement to decide whether to act as an add or edit depending on whether the $this->data['MyModel']['id'] is set.
I think that covers it - if I think of anything else I'll add it in.
My work pattern tends to be to build the edit view, then copy and paste to create the basis for the add view.
this code will check if you have admin_form.ctp or form.ctp which will make it use the same code for add / edit
https://github.com/infinitas/infinitas/blob/dev/app_controller.php#L389
1.3 submits the forms automatically to where the are from so when you go to /edit/1 it will post to there, and /add will post to add.
that is all you need to do. if you have a edit that is vastly different to the add, then you just create the 2 files. when you want them the same, just make the one.
in your app controller
public function render($view = null, $layout = null) {
$viewPaths = App::path('View', $this->plugin);
$rootPath = $viewPaths[0] . DS . $this->viewPath . DS;
$requested = $rootPath . $view . '.ctp';
if (in_array($this->request->action, array('admin_edit', 'admin_add', 'edit', 'add'))) {
$viewPath = $rootPath . $this->request->action . '.ctp';
if (!file_exists($requested) && !file_exists($viewPath)) {
if (strpos($this->request->action, 'admin_') === false) {
$view = 'form';
} else {
$view = 'admin_form';
}
}
}
return parent::render($view, $layout);
}
and in your view you can always check whether its edit or add
if ($this->request->params['action'] == 'admin_edit') {
//do something
}
if ($this->request->params['action'] == 'admin_add') {
//do something
}
in edit.ctp
if($this->data[ModelName]['id']) {
$this->Form->input('id');
}
// create rest of the fields
in Controller::add()
$this->autoRender=false; // at the start of function
$this->render('edit.ctp'); // at the point where you actually want to render
no need to create add.ctp

Resources