dtc66318
2016-04-20 03:31
浏览 29
已采纳

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

I am new to yii2, so in yii2 basic how to view and update records without id value in the url during CRUD

Code:

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,
        ]);
    }
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsij89625 2016-04-20 05:39
    已采纳

    In your view. Create an update button

    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();
    

    Then in your controller

    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,
            ]);
        } 
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题