Yii Framework Forum: [Solved] How To Check, Which Fields Are Updated By The User - Yii Framework Forum

Jump to content

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

[Solved] How To Check, Which Fields Are Updated By The User on update scenario Rate Topic: -----

#1 User is offline   Shahzad 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 21
  • Joined: 16-March 12
  • Location:Islamabad, Pakistan

Posted 12 February 2013 - 07:51 AM

I want to restrict the user to update only some of the fields on update. For this purpose i want to write a validator in the model, which will check if for a restricted field value has been changed from previous value, then this will add an error. How can i check current and previous values for any given field in the model at the time of validation.
0

#2 User is offline   redguy 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 809
  • Joined: 02-July 10
  • Location:Central Poland

Posted 12 February 2013 - 08:00 AM

if you want to disallow user to change some fields, just create new scenario, mark those fields as 'unsafe', and massive assignement will not change them.

if you are looking for some way to check if field was modified - there is no default interface to do this, because previous values are not stored anywhere. You could use behavior to achieve this functionality:
class TrackChangesBehavior extends CActiveRecordBehavior {

    private $oldAttributes = array( );

    function afterFind( $event ) {
        parent::afterFind( $event );
        $this->oldAttributes = $this->owner->attributes;
    }

    /**
     * Checks if specified attribute has changed
     */
    public function isAttributeChanged( $name ) {
        if( $this->owner->getIsNewRecord() ) {
            return false;
        }
        return $this->oldAttributes[$name] !== $this->getOwner()->$name;
    }
}

then attach it to model:
    public function behaviors() {
        return array(
            'TrackChangesBehavior' => array(
                'class' => 'TrackChangesBehavior'
            )
        );
    }

and use pretty simple:
$model = Model::model()->findByPk(1);
$model->attribute = 'new value';
if( $model->isAttributeChanged( 'attribute' ) ) {
  ...
}

red
0

#3 User is offline   Shahzad 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 21
  • Joined: 16-March 12
  • Location:Islamabad, Pakistan

Posted 13 February 2013 - 02:13 AM

Thanks, you guided me well in both of the ways.
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