[Solved] How To Check, Which Fields Are Updated By The User

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.

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' ) ) {

  ...

}



Thanks, you guided me well in both of the ways.