Sunday, 3 June 2012

Sample project in cakephp

Here iam providing a demo site done in cakephp.This post will be more useful for the php newbies. Here iam explaining a project called inventory system. The main logic is simply adding some items and displaying them. By viewing this project you can certainly get some idea about adding,editing in cakephp.ok

so first prepare database:-

--
-- Table structure for table `db_stocks`
--

CREATE TABLE IF NOT EXISTS `db_stocks` (
  `stock_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `productname` varchar(500) DEFAULT NULL,
  `price` int(120) DEFAULT NULL,
  `quantity` varchar(500) DEFAULT NULL,
  `date` date DEFAULT NULL,
  PRIMARY KEY (`stock_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;


now iam explaining this project in the view that users would have a basic understanding about cakephp.

.so configure your database first.
then add a file named index.ctp and copy following code in it:-

<?php  
 $urlRoot=Router::url('/',false);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- include css and js files here -->
</head>

<body>
    <div id="container">
    <div class="headerC">
        <div class="main-headerC">
            <div class="logoC"></div>
                <div class="admin-title"></div>
                <div class="menuC">
                <ul id="menu">
                       
                    </ul>
                </div>
            </div>
        </div>
    <?php echo $content_for_layout;?>
    <div class="footerC">
            <div class="footer">
                Copy Right &copy;    All Rights Reserved.
            </div>
        </div>
    and put this file under app/view/layout folder ..




 then add controller codes specifying under in your controller folder:-
@ create a file named StocksController.php in your /app/controller folder and paste this code their:-
    <?php  
    class StocksController extends AppController   {  
var $uses = array('Stock');  
        function index()  
        { 
            $this->layout="index";
        $stk=$this->Stock->getallstock();
              $this->set('Stocks',$stk);
        }  
    function view()    
        {   
            $this->layout="index";
            $id=$_GET['id'];
            $stockdetails=$this->Stock->getstockdetails($id);
            $this->set('data', $stockdetails);    
        }  
function add()
{
   $this->layout="index"; 
   $data=$this->data;
    if(isset($data['submit'])){
        $productname=trim(strip_tags($data['productname']));
        $price=trim(strip_tags($data['price']));
         $quantity=trim(strip_tags($data['quantity']));
         $date=date('Y-m-d');
          $save['Stock']=array('productname'=>$productname,'price'=>$price,'quantity'=>$quantity,'date'=>$date);
       $this->Stock->save($save);
$this->redirect('/stocks/index');
    }    
}


function edit()    
{    
    $this->layout="index";
    $id=$_GET['id'];
     $stockdetails=$this->Stock->getstockdetails($id);
    $this->set('data', $stockdetails);
    $this->set('id',$id);
    $data=$this->data;
    if(isset($data['submit'])){
      

        $id=$data['id'];
        $productname=trim(strip_tags($data['productname']));
        $price=trim(strip_tags($data['price']));
         $quantity=trim(strip_tags($data['quantity']));
          $save['Stock']=array('productname'=>$productname,'price'=>$price,'quantity'=>$quantity);
       $this->Stock->id=$id;
       $this->Stock->save($save);
$this->redirect('/stocks/index');
    }    

}  
function delete()    
    {   
$this->layout="index";
    $id=$_GET['id'];
    $this->Stock->deleteall($id);
        $this->redirect('/stocks/index'); 
       
    }  

 }  
    ?>  
@ create a file named PagesController.php in your /app/controller folder and paste this code their:-
<?php
/**
 * Static content controller.
 *
 * This file will render views from views/pages/
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('AppController', 'Controller');

/**
 * Static content controller
 *
 * Override this controller by placing a copy in controllers directory of an application
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers/pages-controller.html
 */
class PagesController extends AppController {

/**
 * Controller name
 *
 * @var string
 */
public $name = 'Pages';

/**
 * Default helper
 *
 * @var array
 */
public $helpers = array('Html', 'Session');

/**
 * This controller does not use a model
 *
 * @var array
 */
public $uses = array();

/**
 * Displays a view
 *
 * @param mixed What page to display
 * @return void
 */
public function display() {
$path = func_get_args();

$count = count($path);
if (!$count) {
$this->redirect('/');
}
$page = $subpage = $title_for_layout = null;

if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
if (!empty($path[$count - 1])) {
$title_for_layout = Inflector::humanize($path[$count - 1]);
}
$this->set(compact('page', 'subpage', 'title_for_layout'));
$this->render(implode('/', $path));
}
}
so after that it is time to create view files:-
just add some files as mentioned below:-
@create  index.ctp file in /app/view/Stocks folder and paste code like this:-
 <?php  
$urlRoot=Router::url('/',false);
?>
  <h1 align="center">Inventory</h1>  
  <h4 align="center">
    <a href="<?php echo $urlRoot; ?>Stocks/add" ><span style="color:black; background:grey;"> Add new products </span></a>

  </h4>
    <table border="1" background="green" cellpadding="1" cellspacing="2" align="center">  
        <tr>  
            <th>StockID</th>  
            <th>ProductName</th>  
            <th>Price</th>
   <th>Quantity</th>
   <th>Date</th>  
        </tr>  
        <?php 
for($i=0;$i<count($Stocks);$i++){
?><tr>  
            <td><?php echo $Stocks[$i]['Stock']['stock_id']; ?></td>  
            <td><?php echo $Stocks[$i]['Stock']['productname']; ?></td> 
            <td><?php echo $Stocks[$i]['Stock']['price']; ?></td>  
            <td><?php echo $Stocks[$i]['Stock']['quantity']; ?></td>  
              <td><?php echo $Stocks[$i]['Stock']['date']; ?></td>   
            <td>  
<a href="<?php echo $urlRoot; ?>Stocks/view/?id=<?php echo $Stocks[$i]['Stock']['stock_id'];   ?>"> View</a>
            </td>
            <td><a href="<?php echo $urlRoot; ?>Stocks/edit/?id=<?php echo $Stocks[$i]['Stock']['stock_id'];   ?>"> Edit</a>
            </td>
      <td>   
     <td><a href="<?php echo $urlRoot; ?>Stocks/delete/?id=<?php echo $Stocks[$i]['Stock']['stock_id'];   ?>"> Delete</a>
            </td>
        </td>    
            
          
      </tr>  
  <?php  } ?>
    </table>  
@create  add.ctp file in /app/view/Stocks folder and paste code like this:-
<?php  
$urlRoot=Router::url('/',false);
?>
<h1 align="center">Add inventory</h1>    
<form action="<?php echo $urlRoot;?>Stocks/add/" method="post" name="addform">    
   
    <table border="1" background="green" cellpadding="1" cellspacing="2" align="center">  
    <tr><td>Product name: </td><td>    
            <input type="text" name="productname" />   
        </td></tr>    
       <tr><td>Price: </td><td>      
           <input type="text" name="price"/>     
        </td></tr>    
   <tr><td>Quantity </td><td> 
     
    <input type="text" name="quantity" />   
  </td></tr>
        <tr><td></td><td> 
            <input type="submit" name="submit" value="submit"/>   
        </td></tr>    
    </form>      
@create  edit.ctp file in /app/view/Stocks folder and paste code like this:-
<?php  
$urlRoot=Router::url('/',false);
?>
<h1 align="center">Edit Note</h1>    
<form action="<?php echo $urlRoot;?>Stocks/edit/?id=<?php echo $id; ?>" method="post" name="edit form">    
   <input type="hidden" name="id" value="<?php echo $id;  ?>"/>   
   <table border="1" background="green" cellpadding="1" cellspacing="2" align="center">  
    <tr><td>Product name: </td><td>    
            <input type="text" name="productname" value="<?php echo $data[0]['Stock']['productname']; ?>"/>   
        </td></tr>    
       <tr><td>Price: </td><td>      
           <input type="text" name="price" value="<?php echo $data[0]['Stock']['price']; ?>"/>     
        </td></tr>    
<tr><td>Quantity </td><td> 
  
 <input type="text" name="quantity" value="<?php echo $data[0]['Stock']['quantity']; ?>"/>   
</td></tr>
        <tr><td></td><td> 
            <input type="submit" name="submit" value="submit"/>   
        </td></tr>    
    </form>      
   @create  view.ctp file in /app/view/Stocks folder and paste code like this:- 
     <?php  
$urlRoot=Router::url('/',false);
?>
    <h1 align="center"><?php echo $data[0]['Stock']['productname']?></h1> 
     <table border="1" background="green" cellpadding="1" cellspacing="2" align="center">     
    <tr><td>Price: </td><td> <?php echo $data[0]['Stock']['price']?></td></tr>
     <tr><td>Date: </td><td>   <?php echo $data[0]['Stock']['date']?></td></tr>
   <tr><td>Quantity: </td><td>  <?php echo $data[0]['Stock']['quantity']?></td></tr>
     
<tr><td> </td><td> <a href="<?php echo $urlRoot; ?>Stocks/index/"> <span style="color:black; background:grey;">Back to index</span></a></td></tr>
<tr><td> </td><td> <a href="<?php echo $urlRoot; ?>Stocks/edit/?id=<?php echo $data[0]['Stock']['stock_id'];   ?>"> <span style="color:black; background:grey;">Edit</span></a></td></tr>

 Now its time to create model:-
Stock.php in /app/Model/
<?php  
class Stock extends AppModel  {
      public $name        =   'Stock';
    public $useTable    =   'stocks';
    public $primaryKey  =   'stock_id';


function add()
{
    if (!empty($this->data))
    {
        if ($this->Stock->Save($this->data))
        {
            ($this->flash('Your Inventory has been added!', '/Stocks/'));
        }
        else {
            debug($this->Stock->validationErrors);
        }
    }
}
function getallstock(){
        
        
        $rec    =   $this->find('all',array('conditions'=>array('Stock.stock_id !=""')));
        return $rec;
    }
    function getstockdetails($id){
        
        $rec    = $this->find('all',array('conditions' => array('Stock.stock_id !="" ','Stock.stock_id' =>$id)));
        return $rec;
    }
    function deleteall($id)
    {
        $this->delete($id=$id, $cascade=false);
    }
}
?>
now run your code......

Download Project From Here:- https://github.com/litto/Cakephp-CRUD-Sample-Project
   




3 comments:

  1. hey thanks its realy worked for me......

    ReplyDelete
  2. and the layout/index.php ???

    ReplyDelete
  3. @mario Beradinucci It's already added at the top of the post... please refer it again

    ReplyDelete