replace data from same id user in Yii framework

2019-08-21 11:31发布

how i can fix this error ? i have problem replace data from same id this is my _from :

<div class="row buttons">
    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Update'); ?>
</div>

and this is my Controller action Create :

public function actionCreate()
{
    $model=new TblUasUts;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['TblUasUts']))
    {
        $model->attributes=$_POST['TblUasUts'];
        if($model->save())
            $this->redirect(array('view','id'=>$model->nim_mhs));
    }

    $this->render('update',array(
        'model'=>$model,
    ));
}

this is what i getting error :

CDbCommand gagal menjalankan statementSQL: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '2010140360' for key 'PRIMARY'

2条回答
聊天终结者
2楼-- · 2019-08-21 11:50

Remove save with update:

<div class="row buttons">
    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Update'); ?>
</div>

and this is my Controller action Create :

public function actionCreate()
{
    $model=new TblUasUts;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['TblUasUts']))
    {
        $model->attributes=$_POST['TblUasUts'];
        if($model->update())
            $this->redirect(array('view','id'=>$model->nim_mhs));
    }

    $this->render('update',array(
        'model'=>$model,
    ));
}

Also check have you made your ID field auto increment and primary as well.

查看更多
Rolldiameter
3楼-- · 2019-08-21 12:01

It happens becouse you try to save element with existing Primary Key id. if you want to update existing entry in DB you should load ActiveRecord from DB(TblUasUts::model()->findByPk). Also you can unset field id from into $_POST array and create new row in DB every time.

public function actionCreate()
{
$model=new TblUasUts;

// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);

if(isset($_POST['TblUasUts']))
{
    if (isset($_POST['TblUasUts']['id']) && $_POST['TblUasUts']['id']) {
        $model = TblUasUts::model()->findByPk((int)$_POST['TblUasUts']['id']);
    }

    $model->attributes=$_POST['TblUasUts'];
    if($model->update())
        $this->redirect(array('view','id'=>$model->nim_mhs));
}

$this->render('update',array(
    'model'=>$model,
));

}

查看更多
登录 后发表回答