Bookcafe

Sunday, August 1, 2010

CakePhp : Three Basic Functions

From all my readings, I found out there are three basic codes for functions in CakePhp as to are to add, to edit and to delete data. The codes are all similar in all the books that I have read. All these functions are put into
models_controller.php files.

//To save/add data

function add()
{ if (!empty($this->data)) { $this->Modelname->create(); if(!!$this->Modelname->save($this->data)) { $this->Session->setFlash('Your data is Saved!', true); $this->redirect(array('action'=>'index')); } } }
//To Edit Data
function edit($id=null)
{
if (!$id && empty($this->data))
{
$this->Session->setFlash('Invalid Data', true);
$this->redirect(array('action'=>'index'));
}
if (empty($this->data))
{
$this->data = $this->Modelname->read(null, $id);
}
else
{
$this->Modelname->create();
if(!!$this->Modelname->save($this->data))
{
$this->Session->setFlash('Data is Updated!', true);
$this->redirect(array('action'=>'index'), null, true);
}
}
}
}
//To Delete Data
function delete($id = null)
{
if (!$id)
{
$this->Session->setFlash('Invalid Data', true);
}
else
if($this->Modelname->del($id))
{
$this->Session->setFlash('Data is deleted', true);
}
else
{
$this->Session->setFlash('Could not delete data', true);
}
$this->redirect(array('action'=>'index'));
}
}

Modelname is the name of the model of your CakePhp project and index is the frontpage or the dashboard of your web where you want to redirect your page after these actions.

No comments:

Post a Comment