Showing posts with label CakePHP Scaffold. Show all posts
Showing posts with label CakePHP Scaffold. Show all posts

Thursday, November 12, 2009

CakePHP - Fine-tune Your Scaffolded Application

In my previous post, I tried to explain how you can create a workable application on the fly using scaffolding. Now I'll try to show you how to fine tune your scaffolded application. Since, I'll be referring to my previous post a lot, so, please read that first.


Control Display Fields

In our previous example, say, I want to display only the comments title, body, and created fields. So, I will add the following lines in comments_controller.php (found under '/app/controllers') just below
   var $scaffold;
statement.


function beforeRender() {
if($this->action === 'index'){
$this->set( 'scaffoldFields', array( 'title', 'body', 'created' ) );
  }
}


Note 'beforeRender()' is a CakePHP callback. It gets executed before the actual controller action. This helps you to add some more logic in your controller. There are three controller callback methods in common use: beforeFilter(), beforeRender(), afterFilter()

And here is that much desired screenshot:


For a more detailed discussion, please go through the book.

How to develop a PHP Application on the FLY Application scaffolding with CakePHP

Application scaffolding is a technique that allows a developer to define and create a basic application that can create, retrieve, update and delete objects.
CakePHP allows application scaffolding on the fly. With this technology we can develop a workable application on the fly.
We have already created 'add', 'edit', 'delete', and 'view' methods for 'posts' table.
Let us create another table, 'comments'.

SQL:


CREATE TABLE `comments` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `title` char(50) NOT NULL,
  `body` text NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY  (`id`)
)

Now create the model file.
Step:
1. Create a new file.
2. Copy-paste following lines:
<?php
class Comment extends AppModel {
var $name = 'Comment';
}
?>
3. Save the file as '/app/models/comment.php

Now create the controller file.
1. Create a new file.
2. Copy-paste following lines:

<?php
class CommentsController extends AppController {

var $name = 'Comments';
var $scaffold;
}
?>

3. Save the file as '/app/controllers/comments_controller.php'

Note:
Please note  $scaffold variable. It tells Cake to create a workable application on the fly.
And that's it.

Now point your browser to:
http://caketest.local/comments

You can see a full featured comments application with 'add', 'view', 'edit', 'delete' option.

Here is a screenshot:
In my next post, I'll try to demonstrate how can you fine-tune your scaffolded application.

Cheers!