Home CakePHP

CakePHP 2.x Pagination Tutorial: Helper, Conditions, Limit, Sorting and More!

CakePHP Pagination is one of the fastest thing you can code with this amazing framework. In this post I’m gonna show you how you can create a pagination script in matter of few minutes, or even seconds! Cool? Let’s get started.

This post is part of my CakePHP tutorial series, before you proceed to this, make sure you already installed your CakePHP poperly, know the CakePHP classes and naming conventions, and much better if you can code the CakePHP CRUD operations.

Video Demo

Here’s a video demo of what will be our code ouput.

Controller Code

On our controller, we are going to have a query the cakePHP way, we are going to have the following conditions:

  • Won’t include the record with an ID of 6 (‘conditions’ => array(‘User.id !=’ => ’6′))
  • We will limit to 3 records per page (‘limit’ => 3)
  • Order the result by ID (‘order’ => array(‘id’ => ‘desc’)) in descending order

So here’s the code that will be added in our UsersController.php

public function view() {

    // we prepare our query, the cakephp way!
    $this->paginate = array(
        'conditions' => array('User.id !=' => '6'),
        'limit' => 3,
        'order' => array('id' => 'desc')
    );
    
    // we are using the 'User' model
    $users = $this->paginate('User');
    
    // pass the value to our view.ctp
    $this->set('users', $users);
    
}

The $users variable gives us an array that look like this:

cakephp-pagination

View Code

On our view.ctp, our data is presented with a table. The table header contains the paginator sort() method for sorting the data using any fields you want (and you won’t have to create another query!)

The $this->Paginator object (pagination helper) also has lots of methods for paging, please see the ‘pagination section’ on the code block below.

Also we used the <div class=’paging’> which uses the CakePHP generic CSS. You can change that if you want and be creative with your paging UI design.

<?php
// so we use the paginator object the shorter way.
// instead of using '$this->Paginator' everytime, we'll use '$paginator'
$paginator = $this->Paginator;

if($users){

    //creating our table
    echo "<table>";

        // our table header, we can sort the data user the paginator sort() method!
        echo "<tr>";
        
            // in the sort method, ther first parameter is the same as the column name in our table
            // the second parameter is the header label we want to display in the view
            echo "<th>" . $paginator->sort('id', 'ID') . "</th>";
            echo "<th>" . $paginator->sort('firstname', 'Firstname') . "</th>";
            echo "<th>" . $paginator->sort('lastname', 'Lastname') . "</th>";
            echo "<th>" . $paginator->sort('username', 'Username') . "</th>";
        echo "</tr>";
        
        // loop through the user's records
        foreach( $users as $user ){
            echo "<tr>";
                echo "<td>{$user['User']['id']}</td>";
                echo "<td>{$user['User']['firstname']}</td>";
                echo "<td>{$user['User']['lastname']}</td>";
                echo "<td>{$user['User']['username']}</td>";
            echo "</tr>";
        }
        
    echo "</table>";

    // pagination section
    echo "<div class='paging'>";

        // the 'first' page button
        echo $paginator->first("First");
        
        // 'prev' page button, 
        // we can check using the paginator hasPrev() method if there's a previous page
        // save with the 'next' page button
        if($paginator->hasPrev()){
            echo $paginator->prev("Prev");
        }
        
        // the 'number' page buttons
        echo $paginator->numbers(array('modulus' => 2));
        
        // for the 'next' button
        if($paginator->hasNext()){
            echo $paginator->next("Next");
        }
        
        // the 'last' page button
        echo $paginator->last("Last");
    
    echo "</div>";
    
}

// tell the user there's no records found
else{
    echo "No users found.";
}
?>

Thanks for reading this tutorial code for pagination in CakePHP!

Home CakePHP

CakePHP Classes and Naming Conventions

1.0 Introduction

After installing CakePHP on your server, we now have to learn how to create CakePHP classes and its naming conventions. CakePHP uses Model–view–controller (MVC) software architecture which is really great. If you have no idea what MVC is, I think Wikipedia can give you a great overview. Also, you’re going to get the hang of it in this post.

2.0 Creating CakePHP MVC Files

In this example, we are going to use a database with “users” table and create code for the model, view and controller files. Let’s have fun!

2.1 Preparing the user’s table

Our users table will have only 5 fields which include: id, firstname, lastname, username, password.

CakePHP Classes and Naming Conventions

CakePHP requires a naming convention for our tables. It must be in plural form always. Like right now, we are going to have a table that stores data of users, it means that the name of our table must be “users“, NOT the singular “user” or something.

2.2 Creating a Model

A CakePHP model class manages your application data, rules of validity (for example, a username is required, or a password must consist of letters and numbers) and interactions (queries, etc.).

To create our CakePHP model, go to your app/Model directory, I found mine in C:wampwwwCakePhpProjappModel

On that directory, we will create a model file named “User.php

cakephp-model-naming-convention

CakePHP requires us to create a model file with singular name and with a .php extention, that’s how we come up with the filename “User.php”

If your model has more than one word, for example you have a table “user_permissions”, our Model filename will be camel cased and will look like “UserPermission.php”

Inside that file, we are going to have the Model basic code:

<?php
class User extends AppModel {

    public $name = 'User';
    
}
?>

2.3 Creating a View

A view in CakePHP is the output representation of data retrieved from the model and manipulated by the controller. It can be in the form of HTML, XML, JSON or even PDF!

To create our CakePHP view, we have to go to the app/View/ directory and create a directory called “Users”.

cakephp-view-directory

And then after creating the directory, we will now create the actual “view”, as an example, we are going to have “hello_user.ctp” and leave it as an empty file for now.

cakephp-ctp-file

CakePHP requires us to name a view with a .ctp extension. A view’s name is the same as its function in the controller. We’re going to see it later.

2.4 Creating a Controller

A CakePHP controller class is like the middleman between the Model and View. Controllers are used to manage the logic around a model, and it uses the View for that logic’s output.

To create a model, we are going to create a file named “UsersController.php”

cakephp-controller-file

We are going to have the controller’s basic code:

<?php
class UsersController extends Controller {
    

    
}
?>

3.0 Making MVC Work

Now that we have the required directory, files and basic code inside them, we are going to make this MVC thing work.

3.1 Playing with the controller

First, open your controller, add the following code:

   public function hello_user(){
    
        $user = $this->User->findById(1);
        $this->set('user', $user);

    }

What just happened? As I said earlier, the view name (hello_user.ctp) will be the function name in the controller.

In this function, we tried to retrieve the record details of a user with an ID of 1.

$user = $this->User->findById(1);

To use the $user in the View, we have to use the $this->set() method. Yes, in CakePHP, passing variable values to view requires a $this->set() method.

3.2 Using the Model

For our model, we’ll leave it as is for now. It is used implicitly here in our example. How? Did you see the code $this->User in the controller? Yes, the “User” part of that code is the Model.

3.3 Viewing the View

Lastly, our view “hello_user.ctp” will present the data retrieved, we are going to have this code inside:

<?php
echo "Hello, " . $user['User']['firstname'] . "!";
?>

We retrieved the firstname like that. The $user variable gave us an array value, findById() method gave us this:

array(
    'User' => array(
        'password' => '*****',
        'id' => '1',
        'firstname' => 'Mike',
        'lastname' => 'Dalisay',
        'username' => 'ninjazhai'
    )
)

4.0 Run Code

Now here’s the exciting part, running our code. Go to your browser and type localhost/CakePhpProj/users/hello_user/

You should see something like.

cakephp-classes-name-convention-output

You might want to check out how to perform CRUD in CakePHP.

If you have any comment, suggestion or issues, just drop a comment below. :)

Home CakePHP

How To Use CakePHP Framework, A Getting Started Guide!

1.0 Introduction

Using CakePHP Framework is one of my most favorite things to do. This is the first PHP framework I worked with, and until now, I’m still delighted by it. Now it is time for me to share my knowledge in CakePHP web development.

I think you are here because you already know what CakePHP is, but for those who has no idea yet, and don’t want to read more on CakePHP.org, here’s a brief description: CakePHP makes building web applications simpler, faster and require less code.

I think there are really few blog posts out there with regards to beginner CakePHP tutorials. Most of them are also outdated. We will keep this CakePHP posts as updated as possible. So to the future reader of these posts, please drop something in the comment section below if you think there is something outdated!

We will start with the most basic thing to advanced. Hopefully I can finish this tutorial series in the shortest time possible.

2.0 Install CakePHP on Your Server

Below are few steps to make CakePHP alive in your hosting server, see sections 2.1 to 2.4 below.

By the way, if you’re a super beginner and using a windows PC (localhost), you can follow this tutorial first to set up your localhost: 3 Steps to Install WAMP on Windows

2.1 Download CakePHP (Step 1)

So… what do you expect the first step will be? Of course, we will download the framework. Download the latest CakePHP version here: http://cakephp.org/

As of this writing, the version is CakePHP 2.3.6 stable.

Extract the ZIP file.

2.2 Put CakePHP on Your Hosting (Step 2)

I don’t know, but I think most of you guys are using a localhost (your PC or something). Okay, so I’ll assume you are all using your localhost. If you’re not, just give a comment so we can try help you with your issue.

After you download and extract the Framework files, you have to put it in your root directory. I’m using windows 8 and running with WAMP server, so in my case, my root directory is in:

C:\wamp\www\

Now after putting the extracted folder, my CakePHP directory is in:

C:\wamp\www\cakephp-cakephp-b81c198\

Of course, we want to change the dirty name “cakephp-cakephp-b81c198″ to our “project name”.

So we have to rename it and for this tutorial, we will name it “CakePhpProj”, awesome name right? If you don’t think so, you can choose the project name of your choice. Now we should have:

C:\wamp\www\CakePhpProj

2.3 Run CakePHP

Too early to run? You’re correct. This is just a test run. We just want to confirm if CakePHP can respond at this stage.

So to run CakePHP: Go to your browser > type “localhost/CakePhpProj“

You might see something beautiful like this:

using-cakephp-first-run

You might be disappointed or intimidated by now, but don’t worry, I’m at your side! Proceed to the next step below.

2.4 Configure CakePHP

Alright, so we’re going to address the issues on the previous screenshot, one at a time!

2.4.1 URL rewriting is not properly configured on your server.- Let’s start with this problem, this error is rare if you’re using a real hosting. But if you’re using localhost, here’s the fix:

1. On you notification area (lower right corner), click the WAMP icon.
2. Hover your mouse to the “Apache” folder
3. Hover your mouse to the “Apache modules” folder
4. Find and click “rewrite_module”, WAMP will automatically restart and check that apache module.

mod-rewrite-cakephp

After the fix, re-run our project on the browser, it should look like this now:

cakephp-fix-rewrite-mod

2.4.2 Please change the value of ‘Security.salt’ - To solve this, you have to to got the core.php file and just change the security salt string!

In my case, I have to open it in C:\wamp\www\CakePhpProj\app\Configcore.php

Find the word “salt” (Ctrl+F on your editor, I’m using notepad++)

You should see the line of code that looks like:

Configure::write(‘Security.salt’, ‘DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi’);

Change the value to something like:

Configure::write(‘Security.salt’, ‘nowthisismyawesomesaltthatnoonecaneverknowxfs2gu’);

Then re-run the browser:

cakephp-fixed-security-salt

2.4.3 Please change the value of ‘Security.cipherSeed’ - The solution is the same with 2.4.2, just change the value and re-run!

cakephp-fixed-security-cypherseed

2.4.4 Your database configuration file is NOT present. – Now we have to make a database for our CakePHP application. If you need help doing that, here’s a guide: How To Create MySQL Database With PhpMyAdmin

After creating a database, we have to go again to the Config directory, in my case:

C:\wamp\www\CakePhpProj\app\Config

Now you should see a file named “database.php.default” and rename it to just “database.php“

After renaming it, we have to open it with our editor and supply the database details! In the $default array, what usually we have to change are the: database host, login (username), password and database

You would see something like this in default:

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

So we’re going to change it to:

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

Now, re-run our project page in the browser, it should look like this:

cakephp-installation-fix

3.0 Services

Still having hard time? I can personally help you do this for only $5!

That’s it for this post, enjoy and continue your CakePHP web development! Here is a continuation of this post: CakePHP Classes and Naming Conventions

Thanks for reading this How To Use CakePHP Framework, A Getting Started Guide!

Home CakePHP

Creating a CakePHP CRUD Example – Source Code Download and Tutorial

Hey guys, today I just want to update my CakePHP CRUD example or tutorial from 1.3.x to 2.x. Please note that this post can really help you get started with CakePHP database operations but is just meant to be an example, not production-ready code, use and customize it according to your needs.

Using CakePHP 2.x can give us lots of benefits such as improved support for PostgreSql, SQLite and SqlServer, HTML 5 form inputs support in form helper, a sexier default look taking advantage of new CSS 3 features, a lot faster, almost everything is now lazy-loaded, and even on debug mode you will feel your applications flying, more here, here and here.

cakephp crud example

Our post will cover the following contents:

1.0 MySQL Database Table Used
2.0 CakePHP CRUD Example (CakePHP Version 2.x)
2.1 Create a Record
2.2 Read Records
2.3 Update a Record
2.4 Delete a Record

MySQL Database Table Used

Here we are using a "users" table with such fields.

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ;

The default layout was used in this tutorial. It was found in app/View/Layouts/default.ctp

CakePHP CRUD Example (CakePHP Version 2.x)

Below are the actual CakePHP create, read, update and delete (CRUD) operations. This an be your quick reference in case you need it or want someone to learn about it. Enjoy!

Create a Record in CakePHP

Answers the question, how to create a record in CakePHP?

Controller: app/Controller/UsersController.php

public function add(){

    //check if it is a post request
    //this way, we won't have to do if(!empty($this->request->data))
    if ($this->request->is('post')){
        //save new user
        if ($this->User->save($this->request->data)){
        
            //set flash to user screen
            $this->Session->setFlash('User was added.');
            //redirect to user list
            $this->redirect(array('action' => 'index'));
            
        }else{
            //if save failed
            $this->Session->setFlash('Unable to add user. Please, try again.');
            
        }
    }
}

View: app/View/Users/add.ctp

<h2>Add New User</h2>

<!-- link to add new users page -->
<div class='upper-right-opt'>
    <?php echo $this->Html->link( 'List Users', array( 'action' => 'index' ) ); ?>
</div>

<?php 
//this is our add form, name the fields same as database column names
echo $this->Form->create('User');

    echo $this->Form->input('firstname');
    echo $this->Form->input('lastname');
    echo $this->Form->input('email');
    echo $this->Form->input('username');
    echo $this->Form->input('password', array('type'=>'password'));
    
echo $this->Form->end('Submit');
?>

Read Records in CakePHP

This time it answers, how to read records in CakePHP and display it in a table?

Controller: app/Controller/UsersController.php

public function index() {
    //to retrieve all users, need just one line
    $this->set('users', $this->User->find('all'));
}

View: app/View/Users/index.ctp

<h2>Users</h2>

<!-- link to add new users page -->
<div class='upper-right-opt'>
    <?php echo $this->Html->link( '+ New User', array( 'action' => 'add' ) ); ?>
</div>

<table style='padding:5px;'>
    <!-- table heading -->
    <tr style='background-color:#fff;'>
        <th>ID</th>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Username</th>
        <th>Email</th>
        <th>Actions</th>
    </tr>
    
<?php

    
    //loop to show all retrieved records
    foreach( $users as $user ){
    
        echo "<tr>";
            echo "<td>{$user['User']['id']}</td>";
            echo "<td>{$user['User']['firstname']}</td>";
            echo "<td>{$user['User']['lastname']}</td>";
            echo "<td>{$user['User']['username']}</td>";
            echo "<td>{$user['User']['email']}</td>";
            
            //here are the links to edit and delete actions
            echo "<td class='actions'>";
                echo $this->Html->link( 'Edit', array('action' => 'edit', $user['User']['id']) );
                
                //in cakephp 2.0, we won't use get request for deleting records
                //we use post request (for security purposes)
                echo $this->Form->postLink( 'Delete', array(
                        'action' => 'delete', 
                        $user['User']['id']), array(
                            'confirm'=>'Are you sure you want to delete that user?' ) );
            echo "</td>";
        echo "</tr>";
    }
?>
    
</table>

Update a Record in CakePHP

Answers the question, how to edit or update a record in CakePHP?

Controller: app/Controller/UsersController.php

public function edit() {
    //get the id of the user to be edited
    $id = $this->request->params['pass'][0];
    
    //set the user id
    $this->User->id = $id;
    
    //check if a user with this id really exists
    if( $this->User->exists() ){
    
        if( $this->request->is( 'post' ) || $this->request->is( 'put' ) ){
            //save user
            if( $this->User->save( $this->request->data ) ){
            
                //set to user's screen
                $this->Session->setFlash('User was edited.');
                
                //redirect to user's list
                $this->redirect(array('action' => 'index'));
                
            }else{
                $this->Session->setFlash('Unable to edit user. Please, try again.');
            }
            
        }else{
        
            //we will read the user data
            //so it will fill up our html form automatically
            $this->request->data = $this->User->read();
        }
        
    }else{
        //if not found, we will tell the user that user does not exist
        $this->Session->setFlash('The user you are trying to edit does not exist.');
        $this->redirect(array('action' => 'index'));
            
        //or, since it we are using php5, we can throw an exception
        //it looks like this
        //throw new NotFoundException('The user you are trying to edit does not exist.');
    }
    

}

View: app/View/Users/edit.ctp

<h2>Edit User</h2>

<!-- link to add new users page -->
<div class='upper-right-opt'>
    <?php echo $this->Html->link( 'List Users', array( 'action' => 'index' ) ); ?>
</div>

<?php 
//this is our edit form, name the fields same as database column names
echo $this->Form->create('User');

    echo $this->Form->input('firstname');
    echo $this->Form->input('lastname');
    echo $this->Form->input('email');
    echo $this->Form->input('username');
    echo $this->Form->input('password', array('type'=>'password'));
    
echo $this->Form->end('Submit');
?>

Delete a Record in CakePHP

This answers the questions, how to delete a record in CakePHP?

We won't have view for delete because this is triggered only when the user clicked the delete option on the index page and clicked ok on the pop up.

Controller: app/Controller/UsersController.php

public function delete() {
    $id = $this->request->params['pass'][0];
    
    //the request must be a post request 
    //that's why we use postLink method on our view for deleting user
    if( $this->request->is('get') ){
    
        $this->Session->setFlash('Delete method is not allowed.');
        $this->redirect(array('action' => 'index'));
        
        //since we are using php5, we can also throw an exception like:
        //throw new MethodNotAllowedException();
    }else{
    
        if( !$id ) {
            $this->Session->setFlash('Invalid id for user');
            $this->redirect(array('action'=>'index'));
            
        }else{
            //delete user
            if( $this->User->delete( $id ) ){
                //set to screen
                $this->Session->setFlash('User was deleted.');
                //redirect to users's list
                $this->redirect(array('action'=>'index'));
                
            }else{  
                //if unable to delete
                $this->Session->setFlash('Unable to delete user.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }
}

Do you have any questions or suggestions about our CakePHP CRUD example? Feel free to drop it in the comments section below! If it helps you, please like or share it to your friends, thanks!

Home CakePHP

Paginating, Sorting and Displaying Data with CakePHP

Updated last July 15, 2013: CakePHP 2.x Pagination Tutorial: Helper, Conditions, Limit, Sorting and More!

Today I’m going to show you how easy it is for CakePHP to do pagination, sorting and displaying data from the database (I’m using MySQL). Pagination is useful if you have many rows of data, image if you have thousands of records, your page would load slow and it will be very inconvenient for your users to browse that page. Sorting is useful if you want to view your data in alphabetical, ascending or descending order.

We will have our table look like this:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
)

So in our app/models/user.php we will have something like this:

<?php
class User extends AppModel{
    var $name = ‘User’;
?>

A function on our app/controllers/users_controller.php:

    
    //for this example, we display two records per page
    $this->paginate = array(
        ‘limit’ => 2
    );
    
    //we will set it to users variable for the view
    $this->set(‘users’, $this->paginate(‘User’));
}

Our view file on app/views/users/view_users.ctp:

<?php
echo “<div class=’page-title’>Users</div>”; //title
//this ‘add new user’ button will be used for the next tutorial
echo “<div style=’float:right;’>”;
    $url = “add/”;
    echo $form->button(‘Add New User’, array(‘onclick’ => “location.href=’”.$this->Html->url($url).“‘”));
echo “</div>”;
echo “<div style=’clear:both;’></div>”;

if( sizeOf( $users ) > 0 ){ //check if there are user records returned
?>
<table>
    <tr>
        <!–
            Here on the table heading (<th></th>) is where our SORTING occurs,
            User has to click heading label to sort data in ascending or descending order,
            $paginator->sort(‘Firstname’, ‘firstname’); is a CakePHP function that builds the link for sorting
            the first parameter ‘Firstname’ will be the label 
            and the second parameter ‘firstname’ is actually the database field
        –>
        <th style=’text-align: left;’><?php echo $paginator->sort(‘Firstname’, ‘firstname’); ?></th>
        <th><?php echo $paginator->sort(‘Lastname’, ‘lastname’); ?></th>
        <th><?php echo $paginator->sort(‘Email’, ‘email’); ?></th>
        <th><?php echo $paginator->sort(‘Username’, ‘username’); ?></th>
        <th>Action</th>
    </tr>
    <tr>
    <?php
        foreach( $users as $user ){ //we wil loop through the records to DISPLAY DATA
            echo “<tr>”;
                echo “<td>”;
                    //$user is our foreach variable
                    //['User'] is from our model/alias
                    //['firstname'] is the database field
                    echo “{$user['User']['firstname']}“;
                echo “</td>”;
                echo “<td>{$user['User']['lastname']}</td>”;
                echo “<td>{$user['User']['email']}</td>”;
                echo “<td>{$user['User']['username']}</td>”;
                echo “<td style=’text-align: center;’>”;
                    //’Edit’ and ‘Delete’ link here will be used for our next tutorials
                    echo $html->link(‘Edit’, array(‘action’=>‘edit/’.$user['User']['id']), null, null);
                    echo ” / “;
                    echo $html->link(‘Delete’, array(‘action’=>‘delete/’.$user['User']['id']), null, ‘Are you sure you want to delete this record?’);
                echo “</td>”;
            echo “</tr>”;
        }
    ?>
    </tr>
</table>

<?php
    //here is our PAGINATION part
    echo “<div class=’paging’>”;

    //for the first page link
    //the parameter ‘First’ is the label, same with other pagination links
    echo $paginator->first(‘First’);
    echo ” “;
    
    //if there are previous records, prev link will be displayed
    if($paginator->hasPrev()){
        echo $paginator->prev(‘<<’);
    }
    
    echo ” “;
    //modulus => 2 specifies how many page numbers will be displayed
    echo $paginator->numbers(array(‘modulus’ => 2)); 
    echo ” “;
    
    //there are next records, next link will be displayed
    if($paginator->hasNext()){ 
        echo $paginator->next(‘>>’);
    }
    
    echo ” “;
    //for the last page link
    echo $paginator->last(‘Last’);
    
    echo “</div>”;
    
}else{ //if there are no records found, display this
    echo “<div class=’no-records-found’>No Users found.</div>”;
}

?>

Our output will look like this:

Paginating, Sorting and Displaying Data with CakePHP

cakephp-pagination-page-2

Data is displayed, you can click table heading link for sorting and page links are on the bottom part of the page. That’s it!

Home CakePHP

CakePHP: Access Current Controller, Action and Parameters

Hi guys, today I’m going to show you how to access or get CakePHP’s current page controller, action and parameters. I found this useful when high lighting certain elements of a page for example are tabs, sidebars, etc. that tells the user what part of the system or website they are currently in.

CakePHP: Access Current Controller, Action and Parameters

For instance we will have the following URL:

            http://somedomain.com/users/edit/27/

Based on that URL, our controller is users. To access it we will have:

            $current_controller = $this->params['controller'];

Our action is edit and we will access it this way:

            $current_action = $this->action;

Our first parameter is 27, which is the ID of the record to be edited. We can access it by doing:

            $user_id = $this->params['pass'][0];

In case that we have second parameter, we have to access it this way:

            $second_parameter = $this->params['pass'][1];

For the third parameter:

            $third_parameter = $this->params['pass'][2];

and so on…

You can do these codes either in your controller or view files.

Home CakePHP

CakePHP Naming Conventions

CakePHP requires us to follow certain convention. In this way, we will have very uniform system development, have free functionality, and save time over tracking configuration files! :)

1. Create a Model 
  • directory: app/models/
  • filename: post.php 
  • classname: Post
  • extension: class Post extends AppModel

The filenames of models are always singular. And its classnames are CamelCased.

2. Create a Controller 
  • directory: app/controllers/
  • filename: posts_controller.php
  • classname: PostsController
  • extension: class PostsController extends AppController

The filename of a controller is always plural followed by an underscore then the word "controller" (_controller). Classnames are also CamelCased.

3. Creat a View
  • directory: app/views/posts/
  • filename: hello_world.ctp

You will create another view directory for each of your models. In this case, we created a directory called "posts" under app/views/ directory. Filenames are saved with the extension .ctp (I believe its "cake template page"). They are also named after the method/function (action) inside your controller.

If you have more than one word object (ex. Sponsored Member), you may use underscores to name it. In my case, I will name it "sponsored_member".

Model: sponsored_member.php
View: app/views/sponsored_members
Controller: sponsored_members_controller.php