Yii Framework Forum: How to implement logical deletion in table - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

How to implement logical deletion in table Rate Topic: -----

#1 User is offline   fhelix72 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 53
  • Joined: 22-April 09
  • Location:Italy - Vicenza

Posted 05 May 2009 - 08:11 AM

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.'));
}

}


2) 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.
   
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users