Sunday, September 22, 2013

Generate lft and rght values for a cakephp 2.0 tree



If you are using the Tree Behavior sometimes the lft and rght columns get out of sync, especially if you are adding and deleting records during development. Add the following method to your app/app_controller.php your choice.

1:  public function recover_tree() {  
2:      $modelClass = $this->modelClass;  
3:      $recovery = $this->$modelClass->recover();  
4:      if ($recovery) {  
5:        $this->Session->setFlash(__($modelClass . ' reordered.'), 'flash/success');  
6:        $this->redirect(array('action' => 'index'));  
7:      } else {  
8:        $this->Session->setFlash(__('Error recovering ' . $modelClass . ' tree'), 'flash/error');  
9:      }  
10:      exit;  
11:    }  

These methods/actions are meant to be called manually as you feel needed.
Examle : http://localhost/projects/categories/recover_tree


Saturday, August 31, 2013

Advanced CakePHP 2.x installation tutorial

In some situation you might want to develop many application CakePHP with share the same  Cake Libraries on your server filesystem.

In this tutorial I will try to show how to put your Cake libraries in shared location and share them with your apps in Linux or Windows.

1. Download the latest CakePHP 2.x, unzip it upload to share location.
In my tutorial I will be replacing the Cake libraries in
 
Linux:
/usr/share/cakephp2

Windows:
C:/cakephp2


2. Upload the APP folder and its content to your www/homepage root. You do not need to upload anything else.

3. Edit /app/webroot/index.php

Find:
define('CAKE_CORE_INCLUDE_PATH', ROOT . DS . 'lib');
 
Replace with:
 
#Linux 
define('CAKE_CORE_INCLUDE_PATH', DS.'usr'.DS.'share'.DS.'cakephp2'.DS.'lib');
 
#Windows
define('CAKE_CORE_INCLUDE_PATH','C:'.DS.'cakephp2'.DS.'lib');
 

And in all your other apps on the same server, edit the /app/webroot/index.php file and do the same. Rename app folder to your own project name.  Your CakePHP libraries are now shared, and can be utilized from all apps.

Twitter Bootstrap Typeahead with your CakePHP 1.3



In this post will explain how to integrate Twitter Bootstrap Typeahead with your CakePHP 1.3 application.
Make sure you have include jQuery, Bootstrap CSS and Bootstrap Javascript files in your CakePHP application. You can simply do it inside your default.ctp file.


For this example, we will create action index(), typeahead_search() in users_controller.php. We also create view for index.ctp and users_typeahead.ctp.

In this tutorial I’ll use Users controller. I’ll start by creating index() action, here is the code :

 public function index() {  
   //some code  
 }  
 
And here is the view :
1:  <div class="row">  
2:    <div class="span12">  
3:    <!-- Typeahead -->  
4:    <div class="pull-right">  
5:      <input type="text" data-provide="typeahead" id="user-typeahead">  
6:    </div>  
7:  //other code  
8:  </div>  

The next step is to create Javascript object in your layout file. So add this code snippet in your default.ctp file :
1:  <script type="text/javascript">  
2:    var site_url='<?php echo $this->base; ?>';  
3:  </script>  

This snippet of code will create Javascript object which contains the root URL path of CakePHP.
After we have the Javascript object variable, let’s continue by creating the Javascript code. Inside your application Javascript file add these code :

1:  $('#user-typeahead').typeahead({  
2:   source: function (query, process) {  
3:    return $.ajax({  
4:     url: site_url + 'users/typeahead_search',  
5:     type: 'get',  
6:     data: {q: query},  
7:     dataType: 'json',  
8:     success: function (json) {  
9:      return process(json);  
10:     }  
11:    });  
12:   }  
13:  });  

In this code, we initialize the typeahead library and create AJAX request to the typeahead_search action. In the next step, we will create typeahead_search action that will handle AJAX request and return JSON result. Back to our users controller, create the typeahead action which will contain this code :


1:  class UsersController extends AppController {  
2:  var $components = array('RequestHandler');  
3:  public function typeahead_search() {  
4:    if($this->RequestHandler->isAjax())  
5:    $this->RequestHandler->respondAs('json');  
6:    // get the search term from URL  
7:    $term = $this->request->query['q'];  
8:    $users = $this->User->find('all',array(  
9:      'conditions' => array(  
10:        'User.username LIKE' => '%'.$this->params['url']['q'].'%'  
11:      )  
12:    ));  
13:    // Format the result for select2  
14:    $result = array();  
15:    foreach($users as $key => $user) {  
16:      array_push($result, $user['User']['username']);  
17:    }  
18:    $users = $result;  
19:    echo json_encode($users);  
20:  }  
21:  }  

This action will receive the request, search the database for relevant result and return it on JSON format.

Ref Site : http://www.rudylee.com/cbunny2/






Sunday, June 16, 2013

Pagination With Twitter Bootstrap and CakePHP

Pagination element for CakePHP like twitter bootstrap





Code:
 <div class="pagination">  
  <ul>  
   <?php  
   echo ($this->Paginator->current() > 3) ? $this->Paginator->first('first ', array('tag' => 'li')) : '';  
   echo ($this->Paginator->hasPrev()) ? $this->Paginator->prev(__('prev ', true),  
      array('tag' => 'li', 'id' => 'prev' . rand(2, 9000)), null, array('escape' => false)) : '';  
   echo $this->Paginator->numbers(array('modulus' => 7, 'separator' => ' ', 'tag' => 'li'));  
   echo ($this->Paginator->hasNext()) ? $this->Paginator->next(__(' next', true),  
     array('tag' => 'li'), null, array('escape' => false)) : '';  
   echo ((int) $this->Paginator->counter(array('format' => '%pages%')) > 10) ?  
     $this->Paginator->last('last', array('tag' => 'li')) : '';  
   echo $this->Js->writeBuffer();  
   ?>  
  </ul>  
  </div>  

Thursday, May 16, 2013

Using CakePHP FormHelper with Bootstrap Forms

CakePHP's FormHelper helpt to generate forms when making CakePHP applications. As one might assume, this includes generating input elements, like example:

 <form action="">  
 <fieldset>  
 <div class="control-group required error">  
   <label for="Fieldname" class="control-label">Fieldname</label>  
   <div class="controls">  
     <input name="data[Fieldname]" class="form-error" maxlength="255" type="text" value="" id="Fieldname"/>  
     <span class="help-inline">Error message</span>  
   </div>  
 </div>  
 </fieldset>  
 </form>  

The CakePHP code is:


 <?php echo $this->Form->create('ModelName', array(  
   'class' => 'form-horizontal',  
   'inputDefaults' => array(  
     'format' => array('before', 'label', 'between', 'input', 'error', 'after'),  
     'div' => array('class' => 'control-group'),  
     'label' => array('class' => 'control-label'),  
     'between' => '<div class="controls">',  
     'after' => '</div>',  
     'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),  
   )));?>  
 <fieldset>  
 <?php echo $this->Form->input('Fieldname1', array(  
   'label' => array('class' => 'control-label','text'=>'HERE YOU LABEL TEXT')  
   )); ?>  
 <?php echo $this->Form->input('Fieldname2', array(  
   'label' => array('class' => 'control-label','text'=>'HERE YOU LABEL TEXT')  
   )); ?>  
 </fieldset>   
 <?php echo $this->Form->end();?>  

Saturday, May 4, 2013

Bootstrap Typeahead CakePHP 2.0

Integrate Twitter Bootstrap Typeahead with your CakePHP 2.0 application.
You need:
- Cakephp 2.x
- Jquery
- Twitter bootstrap

First the form:
<input data-provide="typeahead" id="user-typeahead" type="text" />

Setting your url base
Put it into default.ctp before </head>
<script type="text/javascript">
  //get url base app
  var site_url='<?php echo $this->base; ?>';

</script>

The Jquery:
Put it into bottom in view

<script>  
$( document ).ready( function(){        
            $('#user-typeahead').typeahead({
                source: function (query, process) {
                    return $.ajax({
                        url: site_url+'/users/typeahead_search',
                        type: 'get',
                        data: {q: query},
                        dataType: 'json',
                        success: function (json) {
                            return process(json);
                        }
                    });
                }
            });  

 });                      
 </script>


UsersController
    public function typeahead_search() {
        $this->autoRender = false;
        $this->RequestHandler->respondAs('json');

        // get the search term from URL
        $term = $this->request->query['q'];
        $users = $this->User->find('all', array(
            'conditions' => array(
                'User.username LIKE' => '%' . $term . '%'
            )
                ));

        // Format the result for input
        $result = array();
        foreach ($users as $key => $user) {
            array_push($result, $user['User']['username']);
        }
        $users = $result;

        echo json_encode($users);
    }


This action will receive the request, search the database for relevant result and return it on JSON format.

Thursday, February 14, 2013

Upload single image or file using Cakephp 1.3

This tutorial for upload image or file using Cakephp 1.3.

Step 1 : Create table name 'uploads'

CREATE TABLE `uploads` (
 `id` CHAR(36) NOT NULL PRIMARY KEY,
 `title` VARCHAR(45) NOT NULL,
 `description` TEXT,
 `filename` VARCHAR(255) NOT NULL,
 `filesize` INT(11) UNSIGNED NOT NULL DEFAULT 0,
 `filemime` VARCHAR(45) NOT NULL DEFAULT 'text/plain',
 `created` DATETIME,
 `modified` DATETIME
);

Step 2 : Create view for 'uploads'
path : /views/uploads/add.ctp

<?php echo $this->Form->create(‘Upload’, array(‘type’ => ‘file’));?>
  <fieldset>
     <legend><?php __(‘Add Upload’); ?></legend>
  <?php
  echo $this->Form->input(‘title’);
  echo $this->Form->input(‘description’);
  echo $this->Form->input(‘file’, array(‘type’ => ‘file’));
  ?>
  </fieldset>
<?php echo $this->Form->end(__(‘Submit’, true));?>

Step 3 : Create controller 'uploads_controller'
path : /controllers/uploads_controller.php

Step 3.1 : create function add()

function add() {
  if (!empty($this->data)) {
   $this->Upload->create();
            if ($this->uploadFile() && $this->Upload->save($this->data)) 
{
                $this->Session->setFlash(__('The upload has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The upload could not be saved. Please, try again.', true));
            }
        }
    }


Step 3.2 :create function uploadFile()
path : /webroot/uploads
make sure create folder 'upload' in webroot and permission access to this folder


function uploadFile() {
  $file = $this->data[‘Upload’][‘file’];
  if ($file[‘error’] === UPLOAD_ERR_OK) {
    $id = String::uuid();
    if (move_uploaded_file($file[‘tmp_name’], APP.’webroot/uploads’.DS.$id)) {
      $this->data[‘Upload’][‘id’] = $id;
      $this->data[‘Upload’][‘filename’] = $file[‘name’];
      $this->data[‘Upload’][‘filesize’] = $file[‘size’];
      $this->data[‘Upload’][‘filemime’] = $file[‘type’];
      return true;
    }
  }
  return false;
}

Step 4 : Create view and function for download

i. create view index.ctp
path : /views/uploads/index.ctp

<h2><?php __('Upload'); ?></h2>
<table cellpadding="0" cellspacing="0">
    <tr>
        <th><?php __('id'); ?></th>
        <th><?php __('title'); ?></th>
        <th><?php __('download'); ?></th>
    </tr>
    <?php foreach ($uploads as $upload): ?>
        <tr>
            <td><?php echo $upload['Upload']['id']; ?>&nbsp;</td>
            <td><?php echo $upload['Upload']['title']; ?>&nbsp;</td>
            <td>
                <?php
                echo $this->Html->link(__('Download', true), array(
                    'action' => 'download', $upload['Upload']['id']));
                ?>&nbsp;</td>
        </tr>
    <?php endforeach; ?>
</table>
 
ii. create function download in uploads_controller.php

 
function download($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for upload', true));
            $this->redirect(array('action' => 'index'));
        }
        $upload = $this->Upload->find('first', array(
            'conditions' => array(
                'Upload.id' => $id,
            )
                ));
        if (!$upload) {
            $this->Session->setFlash(__('Invalid id for upload', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->view = 'media';
        $filename = $upload['Upload']['filename'];
        $this->set(array(
            'id' => $upload['Upload']['id'],
            'name' => substr($filename, 0, strrpos($filename, '.')),
            'extension' => substr(strrchr($filename, '.'), 1),
            'path' => APP . 'webroot/uploads' . DS,
            'download' => true,
        ));
    }

Extra : Show image in view.ctp
path : /views/uploads/view.ctp

$id = $upload['Upload']['id'];
echo '<img src="'.$this->Html->url(array('controller' => 'uploads','action' => 'download',$id)).'"/>';