Single Table data display and Addition and deletion operations (the original from the http://book.cakephp.org/view/329/Getting-Cake can look at their own comparison, the example is more detailed)
1. Obtain the post table of CakePHP learning 2.
2. Post. php under the models directory
<? PHP
Class Post extends appmodel {
VaR $ name = 'post ';
}
?>
Posts_controller.php
<? PHP
Class postscontroller extends appcontroller {
VaR $ name = 'posts ';
// Var $ scaffold;
Function Index (){
$ This-> set ('posts', $ this-> post-> Find ('all '));
}
Function view ($ id = NULL ){
$ This-> post-> id = $ ID;
$ This-> set ('post', $ this-> post-> Read ());
}
Function add (){
If (! Empty ($ this-> data )){
If ($ this-> post-> Save ($ this-> data )){
$ This-> session-> setflash ('your post has been saved .');
$ This-> redirect (Array ('action' => 'index '));
}
}
}
Function Delete ($ id ){
$ This-> post-> Del ($ id );
$ This-> session-> setflash ('Post with ID: '. $ id. 'has been deleted .');
$ This-> redirect (Array ('action' => 'index '));
}
Function edit ($ id = NULL ){
$ This-> post-> id = $ ID;
If (empty ($ this-> data )){
$ This-> DATA = $ this-> post-> Read ();
} Else {
If ($ this-> post-> Save ($ this-> data )){
$ This-> session-> setflash ('your post has been updated .');
$ This-> redirect (Array ('action' => 'index '));
}
}
}
}
?>
3. files under the views directory
Index. CTP
<? PHP echo $ HTML-> Link ('add Post', array ('controller' => 'posts', 'Action' => 'add')?>
<H1> blog posts <Table>
<Tr>
<TH> id </Th>
<TH> title </Th>
<TH> created </Th>
</Tr>
<! -- Here is where we loop through our $ posts array, printing out post info -->
<? PHP foreach ($ posts as $ post):?>
<Tr>
<TD> <? PHP echo $ post ['post'] ['id'];?> </TD>
<TD>
<? PHP echo $ HTML-> Link ($ post ['post'] ['title'],
"/Posts/View/". $ post ['post'] ['id']);?>
</TD>
<TD>
<? PHP echo $ HTML-> Link ('delete', array ('action' => 'delete ', 'id' => $ post ['post'] ['id']), null, 'Are you sure? ')?>
<? PHP echo $ HTML-> Link ('edit', array ('action' => 'edit ', 'id' => $ post ['post'] ['id']);?>
</TD>
<TD> <? PHP echo $ post ['post'] ['created '];?> </TD>
</Tr>
<? PHP endforeach;?>
</Table>
View. CTP
<H1> <? PHP echo $ post ['post'] ['title']?> </H1>
<P> <small> created: <? PHP echo $ post ['post'] ['created ']?> </Small> </P>
<P> <? PHP echo $ post ['post'] ['body']?> </P>
Add. CTP
<H1> Add post <? PHP
Echo $ form-> Create ('post ');
Echo $ form-> input ('title ');
Echo $ form-> input ('body', array ('rows '=> '3 '));
Echo $ form-> end ('Save Post ');
?>
/APP/views/posts/edit. CTP