How to update only specific fields of an active record in Yii?
29,929
Solution 1
You could create a method in your controller something like this:
public function actionUpdate($id) {
$model = $this->loadModel($id, 'User');
if (isset($_POST['User'])) {
$model->setAttributes($_POST['User']);
if ($model->save()) {
$this->redirect(array('view', 'id' => $model->id_user));
}
}
$this->render('update', array(
'model' => $model,
));
}
To summarize, the action performs the following:
- loads the model from the database (with all the values set from the database)
- assigns the values in the form (this will OVERWRITE only the attributes which were sent in the form)
- the model is saved in the database
So, you don't need to have all the model attributes in the form. The ones which are defined in the form, will be changed in the model. All other fields will not be changed because the model is loaded from the database before setting the form changes.
Solution 2
The approach pointed out by mazzucci is more complicated than necessary. Try this:
YourTable::model()->updateByPk($id, array(
'field1' => NewVal1,
'field2' => NewVal2,
'field3' => NewVal3
));
Comments
-
lvil about 4 years
I have a model (ActiveRecord) that has 5 properties (DB columns).
I fetch a specific record and populate a form that has 3 fields (two other fields shouldn't be updated).
Then I change a specific field and press save.How to update the record, not touching the fields that are not in form?
-
Stelian Matei about 11 years@Sanket could you be more explicit about what is not working?
-
Sanket Sahu about 11 yearsI don't remember that right now, I shouldn't judge the answer so fast. Can you please edit the answer (may be add a few spaces). I will just vote the answer as neutral, sorry for the inconvenience. I will try again and let you know.
-
Leto over 9 yearsFine, but onBeforeSave event cannot be triggered by this way.
-
Leto over 9 yearsAny other way to avoid fetching data from DB ?