Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On update, skip certain attributes from updating yii

Tags:

php

model

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();

like image 564
dev1234 Avatar asked Nov 21 '13 06:11

dev1234


2 Answers

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"); 
like image 187
Manquer Avatar answered Sep 30 '22 15:09

Manquer


As mentioned by Manquer, your scenario is probably not set to update. A correct update sequence would involve loading the existing object instance, assigning variables and then saving them. I personally would never just instantiate an object and give it a different scenario, i think that is asking for issues.

// Load the existing object first
$user = User::model()->findByPk(..);
// Assign everything that has either a validation rule or is added as "safe"
$user->attributes = $_POST['User'];
// Save the updated version
$user->save();

Yii knows not to update the 'id' (if it is correctly defined as the primary key in your database). No need to mark it as unsafe. So: Make sure that the instance was loaded from the db ($user->isNewRecord should be FALSE) and that the table has a PK. And then update the attributes you want.

You can also only update specific attributes by "cleaning" $_POST first or when you call save just call it as $user->save(true, array('name', 'body')) to only update the name and body for example.

like image 33
Blizz Avatar answered Sep 30 '22 16:09

Blizz