How to update only specific fields of an active record in Yii?
activerecord, model, php, sql-update, yii
Solution
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.
Problem
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?