Save

Navigation:  Development > Function Reference > Model >

Save

Previous pageReturn to chapter overviewNext page

Save method used to Add or Update data in database table. We can use two method to save data.
 
Save by Variable:

Format App::Model(MODEL)->Save($data);
 
This data variable  formed like $data[MODEL] = array(Field1=Value1,Field2=Value2,Field3=Value3)

 

For example
// Array Format 1
$data['Page'] = array(
  'name' => 'samplepage',
  'title' =>'My Sample Page',
  'description'=>'Sample Data'
)
 
// Array Format 2
$data['Page']['name'] = 'samplepage';
$data['Page']['title'] = 'My Sample Page';
$data['Page']['description'] = 'Sample Data';

 
$obj = App::Model('Page')->Save($data);

 

Save by Magic Method:

This is another convenient process. In the method first we set all field value in Model object then call Save function.
 
Format :

App::Model(MODEL)

    ->set[fieldName1](Value1)
    ->set[fieldName2](Value1)
    ->Save();
 
Example 1: 
$obj = App::Model('Page')
    ->setName('samplepage')
    ->setTitle('My Sample Page')
    ->setDescription('Sample Data')
    ->Save();
 
 
Add/Update Row:
By default Save function insert a new row in table but it update existing row if we set id in save function. 
 
Note: After inserting a row the new id stored in Model Object and update previous data on next attempt so, for repeated insert in same session we set NULL in id field. 
 

// Create New entry update on next attempted
$obj = App::Model('Page')
    ->setName('samplepage')
    ->setTitle('My Sample Page')
    ->setDescription('Sample Data')
    ->Save();
 
// Update entry
$obj = App::Model('Page')
    ->setId(5)
    ->setName('samplepage')
    ->setTitle('My Sample Page')
    ->setDescription('Sample Data')
    ->Save();
 
// Always Create New entry
$obj = App::Model('Page')
    ->setId(null)
    ->setName('sampepage')
    ->setTitle('My Sample Page')
    ->setDescription('Sample Data')
    ->Save();

 

Return Value

After saving model store Id(AUTO INSERT) and Error Report in returned object.
 
$error = $obj->getErrorInfo(); // Return Error
$id= $obj->getId(); // Return id
 

POST Value:

A common example is to create new entry after submission of HTML form. appRain code save all post date in $this->data variable if we submit POST value and element has "data" in the name. See bellow example:
 
HTML

<form method="post" action="<?php echo App::Config()->baseUrl("/page/manage");?>" >
    <input type="data[Page][name]" value="" />
    <input type="data[Page][title]" value="" />
    <input type="data[Page][description]" value="" />
</form>
 
PHP

if(!empty($this->data)){
 
    $obj = $this->Model('Page')->Save($this->data));
    $error = $obj->getErrorInfo();

 
    if (!empty($error)) {
        App::Module('Notification')->Push($error,'error');
        $this->redirect("/page/manage/update/{$id}");
    }
    else {
        App::Module('Notification')->Push("Saved Successfully");
        $this->redirect("/page/manage/add");
    }
}