Showing posts with label cakephp. Show all posts
Showing posts with label cakephp. Show all posts

Saturday, April 22, 2017

Generate PDF in CakePHP 3.x with CakePDF And DomPDF

At first you need to install CakePDF to your project. Add "friendsofcake/cakepdf": "3.2.*" to "composer.json" file under "require" section as follows:

"require": {

    "friendsofcake/cakepdf": "3.2.*"

}

Now open command panel and navigate to project directory and execute:

composer update friendsofcake/cakepdf --lock


Or you can direct execute the command "composer require friendsofcake/cakepdf" to install CakePDF. This command will install a suitable latest version to your project.


Above command will install CakePDF to your project.


Next step is to install DomPDF.


Execute following command to install DomPDF
"composer require dompdf/dompdf".


Installation complete, now add the following line to "config/bootstrap.php" file:


Plugin::load('CakePdf', ['bootstrap' => true]);


Configure::write('CakePdf', [

    'engine' => [
        'className' => 'CakePdf.Dompdf',
        'options' => [
            'print-media-type' => false,
            'outline' => true,
            'dpi' => 96
        ]
    ],
    'pageSize' => 'Letter',
]);
define('DOMPDF_ENABLE_AUTOLOAD', false);
define('DOMPDF_ENABLE_HTML5PARSER', true);
define('DOMPDF_ENABLE_REMOTE', true);


Configuration options:
  • engine: Engine to be used (required), or an array of engine config options
    • className: Engine class to use
    • options: Engine specific options. Currently only for WkHtmlToPdf, where the options are passed as CLI arguments, and for DomPdf, where the options are passed to the DomPdf class constructor.
  • crypto: Crypto engine to be used, or an array of crypto config options
    • className: Crypto class to use
    • binary: Binary file to use
  • pageSize: Change the default size, defaults to A4
  • orientation: Change the default orientation, defaults to portrait
  • margin: Array or margins with the keys: bottom, left, right, top and their values
  • title: Title of the document
  • delay: A delay in milliseconds to wait before rendering the pdf
  • windowStatus: The required window status before rendering the PDF
  • encoding: Change the encoding, defaults to UTF-8
  • download: Set to true to force a download, only when using PdfView
  • filename: Filename for the document when using forced download

Now we can do 3 things with our CakePDF
1. Download PDF
2. Stream PDF to browser
3. Save PDF to our server

Lets go for download & stream PDF:

Add the following code block in "config/router.php" file:


Router::scope('/pdf_download/:id', function (RouteBuilder $routes) {

    $routes->addExtensions(['pdf']);
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'cakePdfDownload']);

});

Now in your "PagesController.php" add below code snippet:


public function cakePdfDownload($name = null)

{
    Configure::write('CakePdf.download', true);
    Configure::write('CakePdf.filename', "MyCustomName.pdf");

}

Now need to create a layout file for pdf. Create "default.ctp" under "Template/Layout/Pdf" directory with following contents:


<?php

use Cake\Core\Configure;
$cakeDescription = 'CakePHP: the rapid development PHP framework';
?>
<!DOCTYPE html>
<html>
<head>
    <?= $this->Html->charset() ?>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?= $cakeDescription ?>:
        <?= $this->fetch('title') ?>
    </title>

    <?= $this->Html->meta('icon') ?>

    <?= $this->Html->css('base.css', ['fullBase' => true]) ?>
    <?= $this->Html->css('cake.css', ['fullBase' => true]) ?>
    <?= $this->Html->css('home.css', ['fullBase' => true]) ?>
    <link href="https://fonts.googleapis.com/css?family=Raleway:500i|Roboto:300,400,700|Roboto+Mono" rel="stylesheet">
</head>
<body class="home">

<header class="row">

    <div class="header-image"><?= $this->Html->image('cake.logo.svg') ?></div>
    <div class="header-title">
        <h1>Welcome to CakePHP <?= Configure::version() ?> Red Velvet. Build fast. Grow solid.</h1>
    </div>
</header>
<div class="row">
    <div class="columns large-12">
        <?= $this->fetch('content') ?>
    </div>
</div>
</body>

</html>

'fullBase' => true for create permanent link to resources.


Now create a file named "cake_pdf_download.ctp" under "Template/Pages/Pdf" directory with any content.


You are done, you browse "http://localhost/cake/pdf_download/invoice.pdf" then a pdf will be downloaded because we set "Configure::write('CakePdf.download', true);" if we set false here as "Configure::write('CakePdf.download', false);" then PDF will not be downloaded but will be rendered in browser itself.






Now go for save PDF to our server:


public function cakePdf()

{
    $CakePdf = new \CakePdf\Pdf\CakePdf();
    $CakePdf->template('cake_pdf', 'default');
    $CakePdf->viewVars($this->viewVars);
    $pdf = $CakePdf->write(APP . 'Files' . DS . 'Output.pdf');
    echo $pdf;die();

}

And finally you are done CakePDF with DomPDF.

Friday, April 21, 2017

Generate PDF in CakePHP 3.x with CakePDF And Wkhtmltopdf

At first you need to install CakePDF to your project. Add "friendsofcake/cakepdf": "3.2.*" to "composer.json" file under "require" section as follows:

"require": {

    "friendsofcake/cakepdf": "3.2.*"

}

Now open command panel and navigate to project directory and execute:

composer update friendsofcake/cakepdf --lock


Or you can direct execute the command "composer require friendsofcake/cakepdf" to install CakePDF. This command will install a suitable latest version to your project.


Above command will install CakePDF to your project.


Next step is to install wkhtmltopdf.


Download wkhtmltopdf from https://wkhtmltopdf.org/downloads.html.


By default CakePdf expects the wkhtmltopdf binary to be located in /usr/bin/wkhtmltopdf. If you are using wkhtmltopdf in Windows, remove any spaces in the path name. For example use C:/Progra~1/wkhtmltopdf/bin/wkhtmltopdf.exe (Your installation location).



Installation complete, now add the following line to "config/bootstrap.php" file:


Plugin::load('CakePdf', ['bootstrap' => true]);


Configure::write('CakePdf', [

    'engine' => [
        'className' => 'CakePdf.WkHtmlToPdf',
        //'binary' => '/usr/bin/wkhtmltopdf', //LINUX
        'binary' => 'C:\PROGRA~1\wkhtmltopdf\bin\wkhtmltopdf.exe', //WINDOWS
        'options' => [
            'print-media-type' => false,
            'outline' => true,
            'dpi' => 96
        ]
    ],
    'pageSize' => 'Letter',
]);


Configuration options:
  • engine: Engine to be used (required), or an array of engine config options
    • className: Engine class to use
    • binary: Binary file to use (Only for wkhtmltopdf)
    • options: Engine specific options. Currently only for WkHtmlToPdf, where the options are passed as CLI arguments, and for DomPdf, where the options are passed to the DomPdf class constructor.
  • crypto: Crypto engine to be used, or an array of crypto config options
    • className: Crypto class to use
    • binary: Binary file to use
  • pageSize: Change the default size, defaults to A4
  • orientation: Change the default orientation, defaults to portrait
  • margin: Array or margins with the keys: bottom, left, right, top and their values
  • title: Title of the document
  • delay: A delay in milliseconds to wait before rendering the pdf
  • windowStatus: The required window status before rendering the PDF
  • encoding: Change the encoding, defaults to UTF-8
  • download: Set to true to force a download, only when using PdfView
  • filename: Filename for the document when using forced download

Now we can do 3 things with our CakePDF
1. Download PDF
2. Stream PDF to browser
3. Save PDF to our server

Lets go for download & stream PDF:

Add the following code block in "config/router.php" file:


Router::scope('/pdf_download/:id', function (RouteBuilder $routes) {

    $routes->addExtensions(['pdf']);
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'cakePdfDownload']);

});

Now in your "PagesController.php" add below code snippet:


public function cakePdfDownload($name = null)

{
    Configure::write('CakePdf.download', true);
    Configure::write('CakePdf.filename', "MyCustomName.pdf");

}

Now need to create a layout file for pdf. Create "default.ctp" under "Template/Layout/Pdf" directory with following contents:


<?php

use Cake\Core\Configure;
$cakeDescription = 'CakePHP: the rapid development PHP framework';
?>
<!DOCTYPE html>
<html>
<head>
    <?= $this->Html->charset() ?>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?= $cakeDescription ?>:
        <?= $this->fetch('title') ?>
    </title>

    <?= $this->Html->meta('icon') ?>

    <?= $this->Html->css('base.css', ['fullBase' => true]) ?>
    <?= $this->Html->css('cake.css', ['fullBase' => true]) ?>
    <?= $this->Html->css('home.css', ['fullBase' => true]) ?>
    <link href="https://fonts.googleapis.com/css?family=Raleway:500i|Roboto:300,400,700|Roboto+Mono" rel="stylesheet">
</head>
<body class="home">

<header class="row">

    <div class="header-image"><?= $this->Html->image('cake.logo.svg') ?></div>
    <div class="header-title">
        <h1>Welcome to CakePHP <?= Configure::version() ?> Red Velvet. Build fast. Grow solid.</h1>
    </div>
</header>
<div class="row">
    <div class="columns large-12">
        <?= $this->fetch('content') ?>
    </div>
</div>
</body>

</html>

'fullBase' => true for create permanent link to resources.


Now create a file named "cake_pdf_download.ctp" under "Template/Pages/Pdf" directory with any content.


You are done, you browse "http://localhost/cake/pdf_download/invoice.pdf" then a pdf will be downloaded because we set "Configure::write('CakePdf.download', true);" if we set false here as "Configure::write('CakePdf.download', false);" then PDF will not be downloaded but will be rendered in browser itself.






Now go for save PDF to our server:


public function cakePdf()

{
    $CakePdf = new \CakePdf\Pdf\CakePdf();
    $CakePdf->template('cake_pdf', 'default');
    $CakePdf->viewVars($this->viewVars);
    $pdf = $CakePdf->write(APP . 'Files' . DS . 'Output.pdf');
    echo $pdf;die();

}

And finally you are done CakePDF with wkhtmltopdf.

Get the Referer URL in CakePHP 3.X

Get Refer URL is not a big task in CakePHP now.

Just do the following to get Refer URL:

echo "Referrer URL=" . $this->referer('/') . "<BR>";

echo "Referrer URL=" . $this->referer('/', true) . "<BR>";

Which will output:

Referrer URL=http://localhost/cake/pages/database_check

Referrer URL=/pages/database_check

How to get complete current URL for Cakephp 3.x

Below are few steps described to get URL inside Cakephp 3.x controller as well as view file. You can get full URL and base URL and current URL inside Controller.

The very first thing is to include Router in your Controller as below:

use Cake\Routing\Router;


public function urls()
{
    echo "<div style=''>";
    echo "Current URL=" . Router::url(null, true);
    echo "<BR>Current URL=" . Router::url(null, false);
    echo "<BR>Current URL=" . $this->request->getUri();
    echo "<BR>Current URL=" . $this->request->getUri()->getPath();
    echo "<BR>Current URL=" . $this->request->getRequestTarget();
    echo "<BR>Full URL=" . Router::url("/", true);
    echo "<BR>Base URL=" . Router::url("/", false);
    die("</div>");
}


And output would like this:

Current URL=http://localhost/cake/pages/urls
Current URL=/cake/pages/urls
Current URL=http://localhost/pages/urls?id=20&name=Pritom
Current URL=/pages/urls
Current URL=/pages/urls?id=20&name=Pritom
Full URL=http://localhost/cake/
Base URL=/cake/

Thursday, March 9, 2017

How to Install CakePHP in XAMPP

CakePHP is a free, open-source, rapid development framework for PHP. CakePHP is most popular PHP frameworks today.

The very first thing is to need download CakePHP from here
Then extract it in xampp/htdocs folder as below screenshot:


Next is to browse application: http://localhost/cake/ which will look like below screenshot:


Now open "C:\xampp\htdocs\cake\app\Config\core.php" and change value of following properties "Security.salt" and "Security.cipherSeed".

It will remove first 2 errors.

Then its time to connect the application to MySQL database. To do so first rename the file "C:\xampp\htdocs\cake\app\Config\database.default.php" to "C:\xampp\htdocs\cake\app\Config\database.php" and edit the file as follows:

class DATABASE_CONFIG {
    public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'root',
        'password' => '',
        'database' => 'cake',
        'prefix' => '',
        'encoding' => 'utf8',
    );
}


And finally:

To change the content of home page, edit: APP/View/Pages/home.ctp.
To change layout, edit: APP/View/Layouts/default.ctp.
You can also add some CSS styles for your pages at: APP/webroot/css.

Tuesday, July 1, 2014

Strict Standards: Non-static method Configure::getInstance() should not be called

I Got this error as follows:

Strict Standards: Redefining already defined constructor for class Object in C:\Xampp\htdocs\webapp\cake\libs\object.php on line 54

Strict Standards: Non-static method Configure::getInstance() should not be called statically in C:\Xampp\htdocs\webapp\cake\bootstrap.php on line 38

I solved this problem by changing in /cake/bootstrap.php.

FIND:
error_reporting(E_ALL & ~E_DEPRECATED);

REPLACE:
error_reporting(E_ALL & ~E_STRICT & ~E_DEPRECATED);

Wednesday, September 4, 2013

Concat two different fields in cakephp in find statement

<?php
$this
->ModelName->virtualFields = array(
    
'full_name' => "CONCAT(ModelName.first_name, ' ', ModelName.last_name)"

);
$list $this->ModelName->find("all", array(
    
"fields" => array(
        
"ModelName.id",
        
"ModelName.full_name"
    
)
));

?>

Thursday, August 8, 2013

CakePHP: Accessing database.php values

$fields = get_class_vars('DATABASE_CONFIG')

print_r($fields['default']);
or you can use; 
 
App::Import('ConnectionManager');
$ds = ConnectionManager::getDataSource('default');
$dsc = $ds->config;

print_r($dsc);
Will output like this:
Array
(
    [persistent] => 
    [host] => localhost
    [login] => root
    [password] => 
    [database] => db_name
    [port] => 3306
    [driver] => mysql
    [prefix] => 
) 

Monday, July 1, 2013

Cakephp get view file content to a variable from controller

use Cake\View\View;

$html = ''; 
$this->autoRender = false; 
ob_start(); 

$view = new View($this->request);
# OR BELOW
$view = new View($this); 

$view->layout = null; 

/* controller name, a folder exists in views folder */ 
$view->viewPath = "FolderName"; 

/* variable send to view file */ 
$view->set("var", $var); 

$html .= $view->render("file_name"); 
/* a file exists in Views/FolderName/ folder/file_name.ctp */ 

ob_end_clean();

Saturday, April 27, 2013

How to use multiple databases dynamically for one model in CakePHP

I put in the app/Controller/AppModel.php

class AppModel extends Model
{
  /**
   * Connects to specified database
   *
   * @param String name of different database to connect with.
   * @param String name of existing datasource
   * @return boolean true on success, false on failure
   * @access public
   */
    public function setDatabase($database, $datasource = 'default')
    {
      $nds = $datasource . '_' . $database;      
      $db  = &ConnectionManager::getDataSource($datasource);

      $db->setConfig(array(
        'name'       => $nds,
        'database'   => $database,
        'persistent' => false
      ));

      if ( $ds = ConnectionManager::create($nds, $db->config) ) {
        $this->useDbConfig  = $nds;
        $this->cacheQueries = false;
        return true;
      }

      return false;
    }
}

And here is how I used it in my app/Controller/CarsController.php:
class CarsController extends AppController
{
  public function index()
  {
    $this->Car->setDatabase('cake_sandbox_client3');
 
    or you can directly use:
    $this->Car->setDataSource('test1'); 
    /* data source name from cofig/database.php */

    $cars = $this->Car->find('all');

    $this->set('cars', $cars);
  }

}

http://stackoverflow.com/questions/13223946/how-to-use-multiple-databases-dynamically-for-one-model-in-cakephp

Monday, April 22, 2013

Sunday, April 21, 2013

Sorting with Set::sort() in CakePHP 1.2

Sorting data returned from a database query

You're probably thinking "Err... idiot... just use the ORDER BY functionality in the model!". Yeah, we could do that, but that's not much fun!
Here is my freshly baked People controller, which gracefully passes some data to my view. Nothing special here.

<?php
class PeopleController extends AppController {

    var $name = 'People';
    
    function index() {
        $this->set('people', $this->Person->find('all'));
    }
    
}
?>
 
The $people array is in the standard format we receive from our model, and has a belongsTo association (Occupation).
Array
(
    [0] => Array
        (
            [Person] => Array
                (
                    [id] => 1
                    [occupation_id] => 2
                    [name] => Harry Potter
                    [birth_date] => 1980-07-31
                )

            [Occupation] => Array
                (
                    [id] => 2
                    [name] => Student
                )

        )

    [1] => Array
        (
            [Person] => Array
                (
                    [id] => 2
                    [occupation_id] => 1
                    [name] => Albus Dumbledore
                    [birth_date] => 1881-08-01
                )

            [Occupation] => Array
                (
                    [id] => 1
                    [name] => Headmaster
                )

        )

    [2] => Array
        (
            [Person] => Array
                (
                    [id] => 3
                    [occupation_id] => 3
                    [name] => Severus Snape
                    [birth_date] => 1959-01-09
                )

            [Occupation] => Array
                (
                    [id] => 3
                    [name] => Professor
                )

        )

)

Default order

Instead of dumping the entire contents of the $people array after each Set::sort() call, I will present the data in a pretty table.
Person.id Person.name Person.birth_date Occupation.id Occupation.name
1 Harry Potter 1980-07-31 2 Student
2 Albus Dumbledore 1881-08-01 1 Headmaster
3 Severus Snape 1959-01-09 3 Professor

Person.birth_date DESC

Set::sort() currently takes 3 arguments - the array to sort, the array value to sort on, and the sort order. As with the other Set methods, we specify the value to sort on using a key path. This makes it super easy to deal with complex arrays.

$people = Set::sort($people, '{n}.Person.birth_date', 'desc');
 

Person.id Person.name Person.birth_date Occupation.id Occupation.name
1 Harry Potter 1980-07-31 2 Student
3 Severus Snape 1959-01-09 3 Professor
2 Albus Dumbledore 1881-08-01 1 Headmaster

Occupation.name ASC

It's just as simple sorting on a value of an associated model, in this case the person's occupation. Unfortunately the sort method doesn't current have a default sort order, so we need to specify this. We can also use the PHP constants, SORT_ASC and SORT_DESC.

$people = Set::sort($people, '{n}.Occupation.name', SORT_ASC);
 

Person.id Person.name Person.birth_date Occupation.id Occupation.name
2 Albus Dumbledore 1881-08-01 1 Headmaster
3 Severus Snape 1959-01-09 3 Professor
1 Harry Potter 1980-07-31 2 Student

Wednesday, February 27, 2013

use multiple database in one cakephp project

Your app/Config/database.php file should look like this

<?php 
class DATABASE_CONFIG {

 public $default = array(
  'datasource' => 'Database/Mysql',
  'persistent' => false,
  'host' => 'localhost',
  'login' => 'root',
  'password' => '',
  'database' => 'spamassassin',
  'prefix' => '',
  //'encoding' => 'utf8',
 );

 public $vpopmail = array(
  'datasource' => 'Database/Mysql',
  'persistent' => false,
  'host' => 'localhost',
  'login' => 'root',
  'password' => '',
  'database' => 'vpopmail',
  'prefix' => '',
  //'encoding' => 'utf8',
 );
}
?> 

Your Model class should look like this to use database "spamassassin"

<?php
class Userpref extends AppModel {
    public $name = 'Userpref';
    var $primaryKey = "prefid";
    public $useTable = 'userpref';
}
?>

Your Model class should look like this to use database "vpopmail"


<?php
class VPopMailSetting extends AppModel {
    public $name = "VPopMailSetting";
    var $useDbConfig = 'vpopmail';
    var $useTable = 'settings';
}
?>