[Cakephp] Cheatsheet Cakephp 3


Description
      this is cheatsheet to fast learn migration from cakephp 2.x to 3.x.


How To

Controller :
2.x => app/controller/nameController.php
3.x => src/controller/nameController.php

Model :
2.x => app/model/mymodel.php
3.x => src/model/table/mymodelTable.php

View
2.x => app/view/NameController/myview.ctp
3.x => src/Template/nameController/myview.ctp



Setup Class Controller:

namespace App\Controller;
use Cake\Controller\Controller;
class myController extends Controller
{
      public function index()
      {
      }
}

Setup Class Model:src/Model/Table/myTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
class myTable extends Table
{
}

use Cake\ORM\TableRegistry;
// Now $articles is an instance of our ArticlesTable class.

$articles = TableRegistry::get('my');

namespace App\Model\Entity;
use Cake\ORM\Entity;
class Article extends Entity
{
}

use Cake\ORM\TableRegistry;
// Now an instance of ArticlesTable.
$articles = TableRegistry::get('Articles');
$query = $articles->find();
foreach ($query as $row) {
    // Each row is now an instance of our Article class.
    echo $row->title;

}


CRUD (Create Read Update Delete)

Add Record :
public function add()
{
     $myEntity = $this->User->newEntity();
     $myuser = $this->User->patchEntity($myEntity, $this->request->data);
     $this->User->save($myuser);
     $this->redirect(array('controller'=>'main','action'=>'index'));
}

Edit Record :
public function edit($id = null)
{
    $myuser = $this->User->get($id);
    if ($this->request->is(['post', 'put'])) {
        $this->User->patchEntity($myuser, $this->request->data);
        if ($this->User->save($myuser)) {
            $this->Flash->success(__('Your myuser has been updated.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('Unable to update your user table.'));
}

Delete Record :
public function delete($id)
{
$this->request->allowMethod(['post', 'delete']);
$myuser = $this->User->get($id);
$this->User->delete($myuser);
$this->redirect(array('controller'=>'main','action'=>'index'));
}


Read Record :
// Manual Join //
$myuser = $this->User->find('all', array('field' => array('User.*,Userdetail.WORKS'),
     'joins' => array(array('table' => 'Userdetail ',
                                                             'alias' => 'Userdetail',
                                                                          'type' => 'left',
                                                                          'foreignKey' => true,
                                                                          'conditions'=> array('User.ID = Userdetail.ID'))),
                                                                          'limit' => 10,
      ));

$myuser->hydrate(true);
$this->set('myuser',$myuser);

// Non - Join with Where condition
$myuser = $this->User->find('all')->where(['User.ID'=>'1']);


Display In View :
<?php foreach ($myuser as $myuser): ?>
    <tr>
<td><?php echo $myuser->ID ?></td>
<td><?php echo $myuser->USERNAME; ?></td>
<td><?php echo $myuser->PASSWORD; ?></td>
<td><?php //debug($myuser) ?></td>
<td>
<?php echo $this->Form->postLink(
                'Delete',
                ['action' => 'hapus', $myuser->ID],
                ['confirm' => 'Are you sure?'])
            ?>
<?php echo $this->Html->link('Edit', ['action' => 'edit', $myuser->ID]) ?>
</td>

    </tr>


Notes : the most think you must know cakephp 3.x : Installation , Location Files (path controller , model , view) and CRUD. and other feature same as ver 2.x. you just need some adaptation.

[Cakephp] Component

Description
      What is component ? component is a separate class or function from cakephp that define by user. it's very usefull if you have class that you want to include in cakephp.

How To
1. Create file component in : app/controller/component/[your files here].
the rules : - name file same as name class
               - the class must extend "component"
               - outside class must be define : App::uses('Component', 'Controller');

for example i want to create custom function for ACL (access control list) :
[1]. create file with name : AclComponent.php
    // the path : app/controller/component/AclComponent.php
[2]. copy paste the code below :
 <?php   
 App::uses('Component', 'Controller');  
 class AclComponent extends Component {  
   public function authorization($role)   
   {  
     switch($role)  
     {  
     case 'ADMIN':   
       return true;  
       break;   
     case 'ROLE1':  
       return false;  
       break;   
     case 'ROLE2':   
       return false;  
       break;  
     }       
   }  
 }  
 ?>  

2. Include your custom class (component) on variable $components, make sure $components declare on app controller , so you not always declare $components in every controller.
 public $components = array('Acl','DebugKit.Toolbar','Session',......);  

3. Now you can access components in any controller , for example because we create ACL we can validate every user from the role they have in beforeFilter function. here's my custom code using for ACL.

 public function beforeFilter(){  
     parent::beforeFilter();  
     // ACL Function based on role  
     if($this->Acl->authorization('YOUR ROLE HERE'))  
     {  
       //if true then do nothing or bypass  
     }  
     else  
     {  
       // if false then force to logout (user attempt hijack from URL)  
       $this->redirect(array('controller'=>'auth','action'=>'logout'));  
     }  
   }  

done , that's all how to create a component using cakephp

[Cakephp-Template] table pagination + Jquery + bootstrap

Description
       this template is use for me :)

How to

CSS
tr
{ /* make sure change cursor when over row , it looks like profesional LOL */
    cursor: pointer;
    cursor: hand;
}

#rowtable:hover
{
    background:#a0dfff;
}

#rowtable.clicked
{ /*it means id='rowtable' class='clicked'*/
    background:#00bfff;
}



Javascript
$().ready(function(){
    $('tr').click(function() {
               $(this).removeClass("clicked");
               $(this).addClass("clicked").siblings().removeClass("clicked");
   });
});

HTML
<div id="container">
          <h2 class="page-header">View User</h2>
          <div class="pagination pagination-large">
            <ul class="pagination">
                <?php
                    echo $this->Paginator->prev(__('prev'), array('tag' => 'li'), null, array('tag' => 'li','class' => 'disabled','disabledTag' => 'a'));
                    echo $this->Paginator->numbers(array('separator' => '','currentTag' => 'a', 'currentClass' => 'active','tag' => 'li','first' => 1));
                    echo $this->Paginator->next(__('next'), array('tag' => 'li','currentClass' => 'disabled'), null, array('tag' => 'li','class' => 'disabled','disabledTag' => 'a'));
                ?>
            </ul>
          </div>
          <table style="margin:0 auto" class="table table-bordered">
              <tr>
                  <th>Username</th>
                  <th>Fullname</th>
                  <th>Role</th>
                  <th>Last Login</th>
                  <th>Login IP Address</th>
                  <th>Status</th>
                  <th>Action</th>
              </tr>
           
              <tr id="rowtable">
                  <td>Admin</td>
                  <td>Mahendra M.W.</td>
                  <td>Administrator</td>
                  <td>10-12-2014</td>
                  <td>xx.xx.xx.xx</td>
                  <td>Aktif</td>
                  <td style="text-align:center">
                      <a class="btn btn-primary" style="width:80px;">Edit</a>
                      <a class="btn btn-primary" style="width:80px;">Disabled</a>
                  </td>
              </tr>
           
              <tr>
                  <th colspan="16" style="text-align:left">
                      <?php echo 'Page '.$this->Paginator->counter(array(
                      'separator' => ' of '
                      ));?>
                  </th>
              </tr>
           </table>
           <?php echo $this->Js->writeBuffer(); ?>
      </div>

[Cakephp] Styling Pagination Number

Description
        Styling pagination number in cakephp framework.

Requirement
       - Understand cakephp pagination

Howto
1. in view use this code :
<div id="paging">
<?php
echo $this->Paginator->prev('Sebelumnya', array('escape' => FALSE,'tag' => "div class='prevnext'"));
        echo $this->Paginator->numbers(array('separator'=>false,'currentTag'=>"div class='paginationCurrentNumber'",'before' => '','after' => '','tag' => "div class='paginationNumber'"));
        echo $this->Paginator->next('Selanjutnya', array('escape' => FALSE,'tag' => "div class='prevnext'"));
?>
</div>

2. in css add this :
.prevnext{
    color:white;
    text-align: center;
    display:inline-block;
    padding-left: 5px;
    padding-right: 5px;
    margin-left: 1px;
    margin-right: 1px;
    border:1px solid black;
    background: rgb(96,108,136); /* Old browsers */
    background: -moz-linear-gradient(top,  rgba(96,108,136,1) 0%, rgba(63,76,107,1) 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(96,108,136,1)), color-stop(100%,rgba(63,76,107,1))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  rgba(96,108,136,1) 0%,rgba(63,76,107,1) 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top,  rgba(96,108,136,1) 0%,rgba(63,76,107,1) 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top,  rgba(96,108,136,1) 0%,rgba(63,76,107,1) 100%); /* IE10+ */
    background: linear-gradient(to bottom,  rgba(96,108,136,1) 0%,rgba(63,76,107,1) 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#606c88', endColorstr='#3f4c6b',GradientType=0 ); /* IE6-8 */
}

.prevnext:hover{
    background: orange !important;
}

.prevnext a:visited,a:link,a:active{
   color:white;
   text-decoration:none !important;
}

.paginationNumber{
    width:20px;
    display:inline-block;
    text-align: center;
    margin-left: 1px;
    margin-right: 1px;
    color:white;
    border:1px solid black;
    background: rgb(96,108,136); /* Old browsers */
    background: -moz-linear-gradient(top,  rgba(96,108,136,1) 0%, rgba(63,76,107,1) 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(96,108,136,1)), color-stop(100%,rgba(63,76,107,1))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  rgba(96,108,136,1) 0%,rgba(63,76,107,1) 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top,  rgba(96,108,136,1) 0%,rgba(63,76,107,1) 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top,  rgba(96,108,136,1) 0%,rgba(63,76,107,1) 100%); /* IE10+ */
    background: linear-gradient(to bottom,  rgba(96,108,136,1) 0%,rgba(63,76,107,1) 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#606c88', endColorstr='#3f4c6b',GradientType=0 ); /* IE6-8 */
}

.paginationNumber a:visited,a:link,a:active{
   color:white;
   text-decoration:none !important;
}

.paginationNumber:hover{
   background: orange !important;
}

.paginationNumber .current{
   background: white !important;
}

.paginationCurrentNumber{
   width:100%;
   height:100%;
   background:red !important;
}


the result :


*Note : don't forget to declare your css in view.


but if you prefer using bootstrap you use this css (found this code in stackoverflow , works great) :
<div class="pagination pagination-large">
            <ul class="pagination">
                <?php
                    echo $this->Paginator->prev(__('prev'), array('tag' => 'li'), null, array('tag' => 'li','class' => 'disabled','disabledTag' => 'a'));
                    echo $this->Paginator->numbers(array('separator' => '','currentTag' => 'a', 'currentClass' => 'active','tag' => 'li','first' => 1));
                    echo $this->Paginator->next(__('next'), array('tag' => 'li','currentClass' => 'disabled'), null, array('tag' => 'li','class' => 'disabled','disabledTag' => 'a'));
                ?>
            </ul>
          </div>

[Cakephp] Helper Form

Deskripsi
How to use form helper

Required 
1. Understand Model , Controller , Routes , view , etc

How To
1. Form helper always write in view.
2. Here's the minimal syntax helper form must have
   $this->Form->create('model',array('url'=>array('controller'=>'myctrl','action'=>'myact',param1,..);
   $this->Form->input('field',array(*attribute*));
   $this->Form->submit('submit',array(*attribute*));
   $this->Form->end();

3.Here's the attribute for input

   - 'div'=>false/true
   - 'label'=>false/true
   - 'style'=>'your css here'
   - 'required'=>'required' // show exception when field is empty on click submit
   - 'maxlength'=>'50' //means 50 character
   - 'type' => 'text/select/textarea/date/hidden'
   - 'value' => 'abc' // fill the value for input object except select and date

    * for attribute type='select', you must add attribute options, for example

      $this->Form->input('field',array('type'=>'select','options'=>array('a','b','c')));

    * for attribute type='date' , you can customize format date like this 

      $this->Form->input('field',array('type'=>'date','dateFormat' => 'DMY'));// it will display current date

      but if you want using another value date instead current date you can write like this

      this->Form->input('field',array('type'=>'date','dateFormat' => 'DMY','dateFormat' => 'DMY','selected' => date('Y-m-d',strtotime('3/19/2014 00:00:00')))); // why Y-m-d because without dateFormat DMY the default is YMD.

[Cakephp] Authentication

Deskripsi
How to implement Authentication (login) using Cakephp Framework 2.X

Required 
1. Understand Form , Model , Controller , Routes

How To
1. Create table in your database and give it name "user", create 3 field : user_id, username , password.
2. Create Model , give it name "testModel.php"

<?php
class testModel extends AppModel
{
    var $useDBConfig = 'default';
    var $name = 'testModel '; //must same with file name
    var $primaryKey = 'id_user'; // primary key table
    var $useTable = 'user'; // same as table name in database
 
    public $validate = array(
        'username' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A username is required'
            )
        ),
        'password' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A password is required'
            )
        ));
}
?>

3. open file in path app/controller/AppController.php
   add code like this :


class AppController extends Controller { //you can find this line in the bottom  

/* Executing All Controller*/
var $uses = array('userlogin');
/* ----- */

public $components = array(
       'Session',
       'Auth' => array(
       'loginAction' => array('controller' => 'autentikasi','action' => 'login'),
       'authenticate' => array(
       'Form' => array(
       'userModel' => 'userlogin',
       'fields' => array('username' => 'username/email',
                          'password' => 'password' )
                       )
                       ),
       'Form','Basic',
       'loginRedirect' => array('controller' => 'Main',
       'action' => 'index'
        ),
       'logoutRedirect' => array(
       'controller' => 'autentikasi',
       'action' => 'login'
       ),
       'authorize' => array('Controller'), // <- activate isAuthorize()
       )
       );

  

 public function beforeFilter(){
        $this->layout = false;
        $this->Auth->deny('*');
        // don't forget to allow the action you'll be execute , if not it always forever loop to login page.
        $this->Auth->allow('login','not_supported');
 }

  

    public function isAuthorized($user) {

        // jika berhasil login , dapatkan data user

        if (isset($user['userlogin']['username']))

        {

            $dataUser = $this->userlogin->find('all', array('fields'=>array('userlogin.username','userlogin.role'),

                                                            'limit' => 10,

                                                            'conditions' => array('userlogin.username' => $user['userlogin']['username'],

                                                                                  'userlogin.password' => $user['userlogin']['password']

                                                                                   ),

                                                            'order'=>array('userlogin.username' => 'ASC')));

                if(!empty($dataUser))

                { 

                    $this->Session->write('login',true);

                    $this->Session->write('username',$dataUser[0]['userlogin']['username']);

                    $this->Session->write('role',$dataUser[0]['userlogin']['role']);

                    return true;

                }

                else

                {

                    $this->redirect($this->Auth->logout()); //force logout if false username and password

                    return false; //return false auth->login

                }

        }

        else

        {

            echo "Session failure please relogin !";

            return false;

        }

    }

}





4. open or create file in path app/controller/testAuthController.php
<?php

class testAuthController extends AppController {
var $uses = array('testModel ');

    public function index() {
                if ($this->request->is('post')) {
                    if ($this->Auth->login($this->request->data))
                   {
                     return $this->redirect($this->Auth->redirect());
                   }
                   else
                  {
                    $this->Session->setFlash(__('Invalid username or password, try again'));
                  }
               }
    }

    public function logout() {
    return $this->redirect($this->Auth->logout()); // this is calling logout redirect for button logout
    }
 
}

5. Now create form login for index action
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('testModel',array('url'=>array('controller'=>'testAuth','action'=>'index'))); ?>
                        <fieldset>
                            <legend>
                            <?php echo __('Please enter your username and password'); ?>
                            </legend>
                            <?php echo $this->Form->input('username'); // this data passing to username auth
                                  echo $this->Form->input('password'); // this data passing to password auth
                            ?>
                        </fieldset>
                        <?php echo $this->Form->end(__('Login'));
?>

6. Create routes for pretty url, open file in app/config/routes
add line :
 Router::connect('/', array('controller' => 'testAuth', 'action' => 'index', 'home'));
Router::connect('/login/*', array('controller' => 'testAuth', 'action' => 'index'));

Note :
1. if user not login , all page cannot be access and always redirect to login page.
2. if success login , all user can access ALL PAGE , to handle this authorization each user, you can use SESSION :)
3. if user logout , automaticly redirect to login page.

Work Greats , Happy Learning...

Note:
- Edited : fix code authentication



[Cakephp] Query Join

Deskripsi
      Berikut adalah cara join manual selain menggunakan relationship pada model , tapi itu tergantung bagaimana style anda dalam mengcoding, selamat belajar

Howto
1. Saya punya database (SQL Server 2005) dengan Spec berikut (contoh)  :
    table :  1. tr_client // transaction table
                         field : - id [PK]
                                  - id_client // this data refers to table ms_client
                                  - transaction

               2. ms_client // base table as master client
                                  - id_client [PK]
                                  - name
                                  - address


Model for tr_client without relationship (standart model) :
   <?php
   class tr_client extends AppModel
   {
    var $name = 'tr_client';
    var $useDBConfig = 'default';
    var $useTable = 'tr_client';
    var $primaryKey = array('id');
    }
   ?>


 2. Basic Statement Join Code :
         'joins' => array(
                                   array('table' => 'table_join',
                                             'alias' => 'alias',
                                             'type' => 'left/right',
                                   'foreignKey' => false/true,
                                      'conditions'=> array('condition here'))),

3. How to Query
   $data = $this->tr_client ->find('all', array(
                                                                   'field' => array(
                                                                                            'tr_client.transaction,
                                                                                            'master_client.name'),
                                                                   'joins' => array(
                                                                                                    array('table' => 'ms_client ',
                                                                                                         'alias' => 'master_client',
                                                                                                              'type' => 'left',
                                                                                                    'foreignKey' => true,
                                                                                                       'conditions'=> array('
                                                                             tr_client.id_client = master_client.id_client
                                                                                                                             '))),
                                                                          'limit' => 10,
                                                       'conditions' => array('
tr_client.transaction' => 'approve'));

look at the green and yellow mark, you can learn it.

hope's this help :D

[Cakephp] Join Using Relationship

Deskripsi
     Mempelajari bagaimana cara menghubungkan relationship antara 2 model yang saling terkait, untuk tutorial kali ini saya akan menghubungkan kedua model melalui perantara foreign key, salah satunya bertindak sebagai base table karena dalam realitanya cara ini yang paling sering digunakan. untuk jenis relation lainnya bisa dipelajari sendiri.

Howto
1. Saya punya database (SQL Server 2005) dengan Spec berikut (contoh)  :
    table :  1. tr_client // transaction table
                         field : - id [PK]
                                  - id_client // this data refers to table ms_client
                                  - transaction

               2. ms_client // base table as master client
                                  - id_client [PK]
                                  - name
                                  - address
 
   Model for tr_client :
   <?php
   class tr_client extends AppModel
   {
    var $name = 'tr_client';
    var $useDBConfig = 'default';
    var $useTable = 'tr_client';
    var $primaryKey = array('id');
    }
   ?>

   Model for ms_client :
   <?php
   class ms_client extends AppModel
   {
    var $name = sm_client';
    var $useDBConfig = 'default';
    var $useTable = 'sm_client';
    var $primaryKey = array('id_client');
   ?>

   Now we create relation between 2 table, we add code at tr_client model,  why ? because that model which need the data, not ms_client model.

what's the code to create relationship ? here's :
    var $belongsTo = array(
                           'ms_client' => array('className' => 'ms_client',
                                                         'foreignKey' => 'id_client'
                           ));
* look at the green mark, you can learn it.


now add the code to tr_client :
 
   <?php
   class tr_client extends AppModel
   {
    var $name = tr_client';
    var $useDBConfig = 'default';
    var $useTable = 'tr_client';
    var $primaryKey = array('id');
 
    var $belongsTo = array(
                           'ms_client' => array('className' => 'ms_client',
                                                         'foreignKey' => 'id_client'
                            ));
    }
   ?>

ok , all done now when you query using statement something like this :
        
$data = $this->tr_client->find('all', array( 'field' => array( 'ms_client.name',
                                                                                       'tr_client.transaction',
                                                                          'limit' => 10,
                                                                          'conditions' => array('
tr_client.id' => '1'),
                                                                          'order'=>array('
ms_client.name=> 'ASC'));

* look at the green mark, we using tr_client model but we can grab field from another model, That's relationship !! easy right ?


what if we have multiple relation ?? how we do that ? look's this code and you'll be understand : 

    var $belongsTo = array(
                           'ZZZ' => array('className' => 'ZZZ',
                                                  'foreignKey' => 'AAA'
                                                 ),
        
                           'XXX' => array('className' => 'XXX',
                                                  'foreignKey' => 'BBB'

                                                 ),
   };


hope's this help :)

[Cakephp] Add CSS and JS File

Deskripsi
           Berikut adalah cara mengembed file external dari css dan js.


Howto
     1. You must have .css and js file.
    
     2. - your css file path : webroot\CakeApp\app\webroot\css\[create or copy here]
         - your script file path : webroot\CakeApp\app\webroot\js\[create or copy here]
    
     3. Add this script to your view
        <?php echo $this->Html->css('style'); // no need .css ?>

        <?php echo $this->Html->script('jquery-1.8.2'); // no need .js?>

     4. now your script and css will connect to view


[Cakephp] Basic Form

Deskripsi
       Form digunakan sebagai interaksi antara user dan system, interaksi berupa inputan yang digunakan untuk berbagai macam keperluan, seperti register , login , penyimpanan data , etc.

Howto
<table border="0" width="500px;" style="margin-left:10px;" cellspacing="2px;">

            <?php echo $this->Form->create('MODEL', array(
                                   'id'=>'ID_FORM',
                                   'url'=>array(
                                                     'controller'=>'controller',
                                                      'action'=>'action')))
            ?>

            <td>USERNAME</td>
            <td style="text-align:left;padding-left:4px;">
            <?php echo $this->Form->input('USERNAME',array('label'=>false,'style'=>'width:370px'))
             ?>
            </td>

        <?php echo $this->Form->submit('submit_button')?>
        <?php echo $this->Form->end()?>

</table>

Explanation :
* normally you don't need the table, this only sample my code when using form in intranet application.

to create form :  $this->Form->create(MODEL,array(OPTION)); // must have at least 1
to create input : $this->Form->input(MODEL,array(OPTION));
to create submit button : $this->Form->submit('submit_button'); // must have at least 1
to create end tag : $this->Form->end() // must have at least 1

for OPTION , you can read online manual.

after you submit form , you form data exist in variable data in controller, how to call :

$this->data;

variable data is an array variable so if you want to see the value :

print_r($this->data);

if you want to change the value :

$this->request->data['xxx']['zzz'] = 'this is the new one'

if you want to save the database :

$this->model->save($this->data);
  

[Cakephp] Ajax Pagination

Deskripsi
      Cara membuat pagination yang disertai ajax, jadi kita ga perlu melakukan refresh page, lumayan mudah.

Howto
controller (in your action)  :
        $this->paginate=array('fields'=>array('model.field1','model.field2'),
                                            'limit'=>100,
                                            'order'=>array('model.field1'),
                                            'conditions'=>array('model.field1'=>'yeah')
                                            );
         $Data=$this->paginate('model');
         $this->set('viewData',$Data);

View :
// on the top of your div table
      <?php
      $this->Paginator->options(array(
      'update' => 'content', // disable this make your pagination without ajax (normal pagination), wrong value parameter can make all of your javascript disable (like jquery bootstrap dll ... ) so its recommend to not use ajax pagination.
      'evalScripts' => true,
      'before' => $this->Js->get('#busy-indicator')->effect('fadeIn', array('buffer' => false)),
      'complete' => $this->Js->get('#busy-indicator')->effect('fadeOut', array('buffer' => false)),
        ));
      ?>

// on the top of table , for pagination number
       <div id="paging">
                <?php
                     echo $this->Paginator->prev('&laquo; Sebelumnya', array('escape' => FALSE));
                     echo ' |';
                     echo $this->Paginator->numbers(array('separator' => false));
                     echo '| ';
                     echo $this->Paginator->next('Selanjutnya &raquo; ', array('escape' => FALSE));
                ?>
        </div>

//sample table body
   <?php foreach($data as $viewData): ?>
        <tr>
             <td><?php echo $data ['XXX']['YYY']?></td>
        </tr>
   <?php endforeach ?>

//on the bottom of div table
<?php echo $this->Js->writeBuffer(); ?>

[Cakephp] Short Fundamental 2

Deskripsi
     Mengenal lebih jauh bagaimana konsep MVC (Model View Controller) pada cakephp yang akan saya jelaskan sesimple mungkin sehingga cepat dimengerti dan dipahami.
     Pada [Cakephp] Short Fundamental yang pertama, sudah dijelaskan MVC secara umum nah sekarang gimana sih pengaplikasian secara mendalam pada cakephp nya ? akan saya berikan point"nya

Step" nya:
1. User request view bedasarkan nama controller dan actionnya yang diambil dari url, sebagai contoh akses:
    www.mydomain.com/login/index
             : Controller
             : Action
 
    Sample code in controller
    <?php
     class loginController extends AppController
     {
         public function index ()
         {
              // action index otomatis dijalankan ketika controller dipanggil 
         }
     }
     ?>


2. Controller dapat mengenali view berdasarkan method (function in class), jika belom ngerti OOP php harap dipelajari terlebih dahulu. here it's

          public function index ()
         {
              // action index otomatis dijalankan ketika controller dipanggil 
         }

3. Karena nama view sudah dikenali maka lokasi file view akan dicari di :
    app/view/controller_name/view_name.ctp
    
   dalam kasus ini maka lokasi filenya :
    app/view/login/index.ctp

4. Satu tambahan lagi, untuk mempassing variable dari Controller ke View  , gunakan syntax ini :
    di Method / Action (penulisan di method controller):
    $this->set('varInView','myvalue');

    di View
     <?php 
            echo $varInView;
     ?>

mudah bukan ? hope this helps :D

[Cakephp] Theme

Deskripsi
      Jika suatu aplikasi web membutuhkan halaman berbeda-beda untuk tiap user / different privilege, akan lebih baik jika menggunakan theme ketimbang pada tampilan view diberi suatu kondisi hal ini dapat mengakibatkan bertambah kompleksnya koding pada view dan juga susah untuk maintenance serta pengembangan kedepan. penggunaan theme dapat mengurangi kompleksitas pada struktur web.

Howto
1. Buat variable global public $theme; di dalam controller tapi di luar action.
2. Untuk penggunaan dalam action caranya seperti ini :
    $this->theme='SamplePage';
3. Controller tidak akan mencari folder dengan nama action yang bersangkutan pada folder view , tetapi mencari nama folder dengan nama Theme nya. sebagai contoh :
    * anda membuat theme dengan spesifikasi seperti ini
       - anda menulis syntax ini $this->theme='SamplePage'; di dalam action bukutamu()
       - anda menggunakan controller MainController
       - maka posisi folder themenya
                            app/view/themed/SamplePage/Main/bukutamu.ctp
       - jika ingin dikombinasikan dengan layout tersendiri juga bisa, misalkan dalam action
         bukutamu() punya layout dengan syntax seperti ini : $this->layout='headerLayout'; 
       - maka posisi folder layout pada themenya
                           app/view/themed/SamplePage/Layouts/headerLayout.ctp
       - jadi di dalam folder themed tadi ada 2 folder : folder Main dan folder Layouts

hope this helps :D

[Cakephp] Method yang sering dipakai di Cakephp


Deskripsi
       Berikut adalah fungsi-fungsi yang sering saya pakai di cakephp pada bagian controller dan view.

How to
In Controller :
* Router::url(array('controller'=>'main','action'=>'logout'), true); // change page
* $this->render(false / true); // execute controller, but disable view
* $this->layout = layout_name / false; // use layout
* $this->theme = theme_name / false; // use theme
* $this->redirect(array('controller'=>'mycontroller','action'=>'myaction')); // redirect page
* $this->request->is('ajax') // check if request is ajax
* $this->request->is('post') // check if request is post
* $this->set('new_variable','value'); // create var to view
* $this->data / $this->request->data
* $this->Session->delete/read/write('mysession')
* $this->Auth->deny('*'); //disable all action , current controller
* $this->Auth->allow('login','not_supported'); //action only , current controller
* Debug($variable)
* App:import('Vendor','tcpdf/tcpdf'); // use tcpdf class

simpan record 1 field

$this->MODEL->id=$id;
$this->MODEL->saveField('FIELD','value');




In View :

$this->Html->meta('icon',$this->Html->url('/favicon.ico'));
$this->Html->css('yourcss');
$this->Html->css('jquery-ui-1.9.0.custom');

membuat link :
<?php echo $this->Html->link('Edit',array('controller'=>'xxx','action'=>'zzz','escape'=>false)) ?>

menambahkan image :
<?php echo $this->Html->image('loading.gif') ?>

membuat button link :
<?php echo $this->Form->button('Logout', array('onclick' => "location.href='/myapp/main/index'")) ?>

membuat button link untuk akses file di folder webroot/files/report/xxx  :
<form method="GET" Action="<?php echo $this->webroot.'files/reports/'.$myuser.'.xlsx'?>">
            <input TYPE="submit" VALUE="Download Report">
</form>

membuat form di view
$this->Form->create('MODEL',array('controller'=>'','action'=>''))
$this->Form->input('field',array(attribute))
$this->Form->submit('value')
$this->form->end()

//table ajax pagination
<?php $this->Paginator->options(array(
'update' => "#location_div_table",
'evalScripts' => true,
'before' => $this->Js->get('#busy-indicator')->effect('fadeIn', array('buffer' => false)),
'complete' => $this->Js->get('#busy-indicator')->effect('fadeOut', array('buffer' => false)),
));
?>

// for pagination
 <th colspan="7" class="tPagination">
                        <div id="paging">
                        <?php
                        echo $this->Paginator->prev('&laquo; Sebelumnya', array('escape' => FALSE));
                        echo ' |';
                        echo $this->Paginator->numbers(array('separator' => false));
                        echo '| ';
                        echo $this->Paginator->next('Selanjutnya &raquo; ', array('escape' => FALSE));
                        ?>
                        </div>
   </th>

//close tag
<?php echo $this->Js->writeBuffer(); ?>

*Note : Update 19/03/2014