I have the following code for actionUpdate:
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
//$this->performAjaxValidation($model);
echo $model->isNewRecord;
if(isset($_POST['Program']))
{
$model->attributes = $_POST['Program'];
if($model->save()){
$this->redirect(array('admin'));
}
}
$this->render('update',array(
'model'=>$model,
));
}
The echo $model->isNewRecord
returns TRUE but the model is not empty. I have an existing model with the given id and the attributes matched the model, so when I call $model->save()
it gives me
CDbException CDbCommand failed to execute the SQL statement: Duplicate entry for key 'PRIMARY'.
I can't find the reason why it is considered as a new record.
Thanks in advance!
Edit:
Here's the code for my loadModel()
function:
public function loadModel($id)
{
$model=Program::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
CActiveRecord performs the isNewRecord test only after performing afterSave().
So at that point in your code $model->isNewRecord was not tested yet.
Maybe in your situation, it is better to set your own flag (or model attribute), since you anyway know that it is not a new record at that point in your code.