Search code examples
phpyiimodel

On update, skip certain attributes from updating yii


i need to stop updating certain value even those are set to POST array. to do that i am using unsafe in yii rules.

array('id', 'unsafe', 'on'=>'update'),

still with this, i am unable to skip the id from updating.

how can this be done with yii?

below is my rules function..

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('name, body, created_date', 'required'),
        array('name', 'length', 'max'=>128),
        array('body', 'length', 'max'=>512),
        array('id', 'unsafe', 'on'=>'update'),
        // The following rule is used by search().
        // @todo Please remove those attributes that should not be searched.
        array('id, name, body, created_date', 'safe', 'on'=>'search'),
    );
}

Update 1

$model->attributes = $_POST['User'];

and i need when saving, to skip certain attributes.

$model->save();


Solution

  • When you are creating the new model instance in your controller you will need to declare the scenario for example if your declaration was something like this

    $myModelInstance = new MyModel();
    

    you will need to change it to

    $myModelInstance = new MyModel('update');
    

    However if you are using one of the find methods of active records to save it then it is set automatically to "update" as here: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-detail

    if you are using some other logic for declaring the model you can simply use the setScenario function

    $myModel->setScenario("update");