When updating, skip some attributes from the yii update

I need to stop updating a specific value, even if they are set to a POST array. I use unsafe yii rules for this.

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

still with this, i cant miss the id from the update.

how can this be done with yii?

below is my function rules.

 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.

$ models-> Save ();

+6
source share
2 answers

When you create an instance of a new model in your controller, you will need to declare a script, for example if your ad was something like this

 $myModelInstance = new MyModel(); 

you will need to change it to

 $myModelInstance = new MyModel('update'); 

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

If you use any other logic to declare a model, you can simply use the setScenario function

 $myModel->setScenario("update"); 
+2
source

As mentioned in Manquer, your script is probably not configured to update. The correct update sequence would include loading an existing instance of the object, assigning variables, and saving them. Personally, I will never just create an instance of an object and give it another scenario, I think it asks questions.

 // 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 does not know 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 the instance was loaded from db ($ user-> isNewRecord must be FALSE) and that the table has PK. And then update the attributes you need.

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

+1
source

Source: https://habr.com/ru/post/958534/


All Articles