在yii2中,尝试在CRUD期间查看和更新url中没有id值的记录


In yii2 trying to view and update records without id value in the url during CRUD

我是yii2的新手,所以在yii2中,如何在CRUD 期间查看和更新url中没有id值的记录

代码:

public function actionView($id)
{
    $model = $this->findModel($id);
    return $this->render('view', [
        'model' => $model
    ]);
}
public function actionUpdate($id)
{
    $model = $this->findModel($id);
    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['index']);
    } else {
        return $this->render('update', [
            'model' => $model,
        ]);
    }
}

在您的视图中。创建更新按钮

echo 
Html::beginForm(['/model/update'], 'post',['id' => 'update-form']) .
'<input type="hidden" name="id" value="'.$model->id.'">
 <a href="javascript:{}" onclick="document.getElementById(''update-form'').submit(); 
return false;">Update</a>'. 
Html::endForm();

然后在你的控制器

public function actionUpdate()
{
    if ( Yii::$app->request->post() ) {
        if ( isset (Yii::$app->request->post()['Model']['id']) ) {
            $id = Yii::$app->request->post()['Model']['id'];
        } else {
            $id = Yii::$app->request->post()['id'];
        }
        $model = $this->findModel($id);
    }
    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['index']);
    } else {
        return $this->render('update', [
            'model' => $model,
        ]);
    } 
}

我们可以通过创建"查看和更新模式"按钮来访问Url中没有id值的查看和更新页面。