Showing posts with label beforeSave. Show all posts
Showing posts with label beforeSave. Show all posts

Saturday, June 15, 2013

YII use beforeSave and beforeValidate function as common for all Model

Create a file suppose named 'MyActiveRecord.php' suppose in 'components' folder.


<?php
class MyActiveRecord extends CActiveRecord {
    public function beforeValidate()
    {
        if(parent::beforeValidate())
        {
            /* Do some common work */
            return true;
        }
    }
    function beforeSave() {
        if (parent::beforeSave()) {
            if($this->isNewRecord) {
                $maxOrderNumber = Yii::app()->db->createCommand()
                ->select('max(id) as max')
                ->from($this->tableName())
                ->queryScalar();
              $this->id = intval($maxOrderNumber) + 1;
            }
        }
        return true;
    }
}
?>

Now create a Model named 'Email' in 'models' folder.
See the highlighted extends object that is the previous one.
The MyActiveRecord does when a new Email inserted to database, set its id as
current id+1 as new id.
<?php
class Email extends MyActiveRecord {
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    public function tableName()
    {
        return 'email';
    }
    public function rules()
    {
        return array(
            array('address, contact_id, contact_user_id', 'required'),
            array('contact_id, contact_user_id', 'numerical'),
            array('address, email_label', 'length', 'max'=>250),
            array('email_label, address', 'safe', 'on'=>'search')
        );
    }
    public function attributeLabels()
    {
        return array(
            "address" => "Address",
            "email_label" => "Category"
        );
    }
    
    public function findByParameters($parameters)
    {
        $criteria=new CDbCriteria;
        foreach ($parameters as $key => $value) {
            $criteria->compare($key, $value,true);
        }                
        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria
        ));
    }
}
?>