How to implement logical deletion in table

I hope this will be useful, it's a proposal for implement a logical deletion of records in a table by using a specific field, so the record are not phisical deleted but a field is set with a specific value that indicate that the record is logically delete.

  1. In 'components' folder I created an extension of CActiveRecord class I call it MyActiveRecord.php and there I override the standard delete function (I assume that in all my tables the field for logical deletion is called 'flagAnn' and

the value for deletion is 'Y', if the field is not found in the table than the function do the standard phisical deletion)

class MyActiveRecord extends CActiveRecord

{

/**


 * Ovverride of delete function, if in the table exists 'flagAnn' field  


 * then it logically deletes the record by saving a value like 'Y' in the field. 


 * @return boolean whether the deletion is successful.


 * @throws CException if the record is new


 */


public function delete()


{


	if(!$this->getIsNewRecord())


	{


		Yii::trace(get_class($this).'.delete()','system.db.ar.CActiveRecord');


		if($this->beforeDelete())


		{

        if ($this->hasAttribute('flagAnn'))

        {

          //logical deletion

          $this->setAttribute('flagAnn', 'Y');

    $result=$this->save();

        } else {

          $result=$this->deleteByPk($this->getPrimaryKey())>0;

		  }


		  $this->afterDelete();

      }

      return $result;

	}


	else


		throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));


}

}

  1. Then in the xxxcontroller.php of my class I change actionList and actionAdmin functions to omit the deleted record

by adding after '$criteria=new CDbCriteria;' this row:         

	if(regioni::model()->hasAttribute('flagAnn')) $criteria->condition='(flagAnn is null or flagAnn = \' \')';

This was a basic example, you can improve it by implementing a function for show or hide the deleted record and then

give the possibility to users to reactivate a record by choosing again delete on a deleted record.