Create Database Table
CREATE TABLE `categories` (
`id` INTEGER(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM
Crate Model app\models\category.php
1 2 3 4 5 6 7 8 9 10 11 | <?php class Category extends AppModel { var $name = 'Category' ; var $validate = array( //validate 'name' => array( 'rule' => 'notEmpty' , 'message' => 'No, no, this field must not be empty!' ) ); } ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php class CategoriesController extends AppController { var $name = 'Categories' ; function index() { $ this ->set( 'categories' , $ this ->Category->find( 'all' )); } function add() { if (!empty($ this ->data)) { if ($ this ->Category->save($ this ->data)) { $ this ->Session->setFlash( 'Your category has been saved.' ); $ this ->redirect(array( 'action' => 'index' )); } } } function delete ($id) { $ this ->Category-> delete ($id); $ this ->Session->setFlash( 'The category with id: ' .$id. ' has been deleted.' ); $ this ->redirect(array( 'action' => 'index' )); } function edit($id = null) { $ this ->Category->id = $id; if (empty($ this ->data)) { $ this ->data = $ this ->Category->read(); } else { if ($ this ->Category->save($ this ->data)) { $ this ->Session->setFlash( 'Your category has been updated.' ); $ this ->redirect(array( 'action' => 'index' )); } } } } ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <!-- File: /app/views/categories/index.ctp --> <h1>Categories</h1> <?php echo $html->link( 'Add Category' ,array( 'controller' => 'categories' , 'action' => 'add' )); ?> <table> <tr> <th>Id</th> <th>Title</th> <th>Actions</th> </tr> <?php foreach ($categories as $category): ?> <tr> <td><?php echo $category[ 'Category' ][ 'id' ]; ?></td> <td> <?php echo $html->link($category[ 'Category' ][ 'name' ], array( 'controller' => 'categories' , 'action' => 'edit' , $category[ 'Category' ][ 'id' ])); ?> </td> <td> <?php echo $html->link( 'Delete' , array( 'action' => 'delete' , $category[ 'Category' ][ 'id' ]), null, 'Are you sure?' )?> <?php echo $html->link( 'Edit' , array( 'action' => 'edit' , $category[ 'Category' ][ 'id' ]));?> </td> </tr> <?php endforeach; ?> </table> |
1 2 3 4 5 6 7 | <h1>Edit Category</h1> <?php echo $form->create( 'Category' , array( 'action' => 'edit' )); echo $form->input( 'name' ); echo $form->input( 'id' , array( 'type' => 'hidden' )); echo $form->end( 'Save Category' ); ?> |
1 2 3 4 5 6 | <h1>Add Category</h1> <?php echo $form->create( 'Category' ); echo $form->input( 'name' ); echo $form->end( 'Save Post' ); ?> |