Auto set model fields values

You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#2)

  1. Scenario
  2. Create new model:
  3. Using new model:

This is a tutorial for how to auto set model values without any code.

Scenario

I was working with admin panel for a big project. There are 4 almost common fields in all database tables.

  • createdDate (When record is added)

  • createdIp (IP address from where record is added)

  • updatedDate (When record is updated)

  • updatedIp (IP address from where record is updated)

From gii i have generated CRUDs. Now for each model/controller i need to update CRUD code for adding above 4 fields. Better write a code in single place and let other models use it.

Create new model:

Create a new model MasterAdmin as shown below, this file will be under common model folder. You can find inline comment for understanding.

<?php
class MasterAdmin extends CActiveRecord
{
    public function beforeSave()
    { 		
		if($this->isNewRecord) // only if adding new record
		{
			if($this->hasAttribute('createdDate')) // if model have createdDate Field
				$this->createdDate = new CDbExpression('NOW()'); // set createdDate value	
			if($this->hasAttribute('createdIp')) // if model have createdIp Field
				$this->createdIp = CHttpRequest::getUserHostAddress(); // set user's ip
		}

		if($this->hasAttribute('updatedDate')) // if model have updatedDate Field
			$this->updatedDate = new CDbExpression('NOW()'); // set updatedDate value	
		if($this->hasAttribute('updatedIp')) // if model have updatedIp Field
				$this->updatedIp = CHttpRequest::getUserHostAddress(); // set user's ip
	    
                return parent::beforeSave();
    }
}
?>

It may be possible all model does not have above 4 fields, then also you can use this model commonly. hasAttribute function will take care of it.

Using new model:

Now when you see all models, it will extend CActiveRecord as shown below.

class User extends CActiveRecord
{

Now change it to below code. Extend newly created model. Don't worry about CActiveRecord, It is already extended at MasterAdmin

class User extends MasterAdmin
{

Even if you don't want to change above code each time, you can change CRUD template as shown below. _ Path: MyProject\framework\gii\generators\model\ModelCode.php

Change

public $baseClass='CActiveRecord';

To

public $baseClass='MasterAdmin';

Now, no need to write any code code for above mentioned 4 fields, MasterAdmin model will take care of it.

You can check more admin panel related help at HERE

Happy Coding! :)