saverbehavior Allows simple saving of related models

  1. Requirements
  2. Usage
  3. Links

SaverBehavior provides two methods:

  1. saveWith - which configures models for relational saving
  2. relationalSave - which saves models and returns false if any of models has not been saved.
    Component saves model inside DB transaction, and it tries to save all models. If saving is not successful component rollbacks transaction.

Requirements

It requires DB engine supporting transactions in the way to get rollbacks working. Also it requires data passed to saveWith method to have correct indexes - i.e. 0,1,2,3 etc.

Usage

See the following code snippet to see how it works.
you should create all models or array of models to be saved, then for the main model you should call saveWith method passing models which needs to be saved with main model, data for those models and the name of the field to save primary/foreign keys. Optional parameter is $processor that should implement "validate" method accepting an array of models. This method will be called to validate an array of related models. For example, if you need verify a sum of payments and each payment is a separate model.

$order = new Order;
$address = new Address;
$user = new User;
$contacts = array(new Contact);
$invoice = new Invoice;
 
if (isset($_POST['Submit'])) {
  	  $user->saveWith($address, $_POST['Address'], 'addressId');
  	  $user->saveWith($contacts, $_POST['Contact'], 'userId'); // here we can add additional parameter to validate all models at once
 	  $order->saveWith($user, $_POST['User'], 'userId');
  	  $invoice->saveWith($order, $_POST['Order'], 'orderId');
  	  $invoice->saveWith($user, $_POST['User'], 'userId');
  	  $invoice->attributes = $_POST['Invoice'];
 	  if ($invoice->relationalSave()) {
  		echo 'True';
  	  } else {
  		echo 'False';
  	  }
}
   $this->render('create',
 	  array('order' => $order,
 	  'user' => $user,
 	  'invoice' => $invoice,
 	  'address' => $address,
 	  'contacts' => $contacts));

To use behavior you should specify path to behavior in the CActiveRecord's method named behaviors:

public function behaviors() {
        return array(
            'SaverBehavior' => array(
                'class' => 'application.components.SaverBehavior'
            ),
        );
    }

Links

  1. http://habrahabr.ru/blogs/yii/118910/ (russian)
10 1
9 followers
592 downloads
Yii Version: 1.1
License: MIT
Category: Database
Developed by: orkon
Created on: May 8, 2011
Last updated: 12 years ago

Downloads

show all

Related Extensions