在yii2中单击按钮时如何更新数据库中的字段?

时间:2018-11-16 06:24:07

标签: php phpmyadmin yii2 yii2-advanced-app

当我单击“右键”按钮时,我想要的是数据库表中“状态”字段中的内容从空更新为“批准”。当我单击按钮“ x”时,数据库表中“状态”字段中的内容将从空更新为“拒绝”。

'buttons' => [

                    'view' => function ($url, $model){
                        return Html::a('<span class ="glyphicon glyphicon-eye-open"></span>', $url, [
                                        'title' => Yii::t('app','view'),
                                        ]);
                    },
                    'approve' => function ($url, $model){
                        return Html::a('<span class ="glyphicon glyphicon-ok-sign"></span>', $url, [
                                        'title' => Yii::t('app','approve'),
                                        ]);
                    },
                    'reject' => function ($url, $model){
                        return Html::a('<span class ="glyphicon glyphicon-remove-sign"></span>', $url, [
                                        'title' => Yii::t('app','reject'),
                                        ]);
                    }
        ],

        'urlCreator' => function ($action, $model, $key, $index) {
                if ($action === 'view') {
                    $url = 'index.php?r=appointment-confirmation/view&id='.$model->appID;
                    return $url;
                }
                if ($action === 'approve') {
                    $url = 'index.php?r=appointment-confirmation/view&id='.$model->appID;
                    return $url;
                }
                if ($action === 'reject') {
                    $url = 'index.php?r=appointment-confirmation/view&id='.$model->appID;
                    return $url;
                }   
        }

这就是它的样子:

1 个答案:

答案 0 :(得分:0)

创建指向changeStatus操作的链接,将状态作为get参数传递:

if ($action === 'approve') {
    return $url = Url::to(['appointment-confirmation/change-status', 'id' => $model->appID, 'status' => 'approve']);
}
if ($action === 'reject') {
    return $url = Url::to(['appointment-confirmation/change-status', 'id' => $model->appID, 'status' => 'reject']);
}

创建操作changeStatus(查找约会,更改状态,重定向到视图):

public function actionChangeStatus($id, $status)
{
    $appointment = Appointment::findOne($id);
    if (!$appointment) {
        throw new HttpException(404);
    }
    $appointment->status = $status;
    if ($appointment->save()) {
        $this->redirect(['view', $id => $appointment->id]);
    } else {
        throw new Exception('Error while saving appointment');
    }
}