Sunday, March 1, 2015

Dropdown Cakephp with Chained Selects Plugin for jQuery and Zepto

http://www.appelsiini.net/projects/chained

Basic setup for Chained Selects Plugin 

1. First you must include jQuery and Chained in your code:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.chained.min.js"></script>

2. Then lets assume you have the following HTML code:

<select id="mark" name="mark">
  <option value="">--</option>
  <option value="bmw">BMW</option>
  <option value="audi">Audi</option>
</select>
<select id="series" name="series">
  <option value="">--</option>
  <option value="series-3" class="bmw">3 series</option>
  <option value="series-5" class="bmw">5 series</option>
  <option value="series-6" class="bmw">6 series</option>
  <option value="a3" class="audi">A3</option>
  <option value="a4" class="audi">A4</option>
  <option value="a5" class="audi">A5</option>
</select>

3. You can now chain the #series to #mark. There are two different ways to do it. Choose yourself if you prefer more english like or shorter version. I prefer the shorter version.

$("#series").chained("#mark"); /* or $("#series").chainedTo("#mark"); */


Basic setup for Chained Selects Plugin in Cakephp

1. Make find('all') in any function of controller for custome dropdown

$states = array();
$country = $this->Application->Country->find('list');
$states_id = $this->Application->States->find('all');

//Custome dropdown states
foreach ($states_id as $key => $value) {
            $states[$key] = array(
                'name' => $value['State']['name'],
                'value' => $value['State']['id'],
                'class' => $value['State']['id'] //class like Chained format
}

$this->set(compact('country', 'states'));

2. Write Select Cakephp Helper From

echo $this->Form->input('country_id', array('empty'=>'--Select--'));            
echo $this->Form->input('state_id',  array(
     'type' => 'select','empty'=>'--Select--', 'options' => $states)
);

3. Write script on bottom of page
<script>
    $(function () {
      $("#ApplicationCountryId").chained("#ApplicationStateId"); 
   });
</script>

Thursday, August 14, 2014

Cakephp code with Count(*) AS Total

1. Create table with name : `activities`

CREATE TABLE IF NOT EXISTS `activities` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `day` varchar(50) NOT NULL,
  `date` date NOT NULL,
  `week` varchar(10) NOT NULL,
  `month` varchar(10) NOT NULL,
  `year` varchar(10) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4976

2. Data Sample : http://pastebin.com/3F41jEpU

3. Create function index in ActivitiesController

class ActivitiesController extends AppController {

    public function index() {
        $this->Activity->recursive = 0;        
        $activities = $this->Activity->find('all', array(
            'fields' => array('Activity.year', 'COUNT(*) AS total'),
            'group' => 'year',
            'order' => array('Activity.year' => 'DESC'),           
        ));       
        $this->set(compact('activities'));
    }


4. Create view for index.ctp

<table cellpadding="0" cellspacing="0">   
        <tr>
            <th><?php echo 'Year'; ?>&nbsp;</th>
            <th><?php echo 'Total'; ?>&nbsp;</th>              
        </tr>
        <?php foreach ($activities as $activity): ?>
            <tr>
                <td><?php echo h($activity['Activity']['year']); ?>&nbsp;</td>
                <td><?php echo h($activity[0]['total']); ?>&nbsp;</td>              
            </tr>
        <?php endforeach; ?>
    </table>

Output:

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>