2017-09-02 22 views
3

例如:如何用視圖中的不同形式創建頁面(yii2)?

我們有表book不同類型(HorrorTravelHistory)。

我們需要爲這些書創建一個方法update,但是對於每種書類型,我們需要顯示不同類型的表單。

我們該如何做到這一點?

以下代碼是否正確?

public function actionUpdate($id) 
{ 
    $model = $this->getType($id); 

    switch ($model->type){ 
     case Book::TYPE_HORROR: 
      return $this->render('update_horror', [ 
       'model' => $model 
      ]); 
      break; 
     case Book::TYPE_TRAVEL: 
      return $this->render('update_travel', [ 

      ]); 
      break; 
     case Book::TYPE_HISTORY: 
      return $this->render('update_history', [ 

      ]); 
    } 

    throw new NotFoundHttpException; 
} 

回答

1

你可以做這樣的事情

public function actionUpdate($id) 
{ 
    $model = $this->getType($id); 

    return $this->render('update_'. $model->type, ['model' => $model]); 

} 

哪裏視圖名稱必須是 「update_」 + exactely $模型 - >鍵入結果,

如:恐怖= update_orror。 php

這是爲了讓視圖更加饒舌,但不要忘記將動作方法添加到窗體中,否則會查找不存在的頁面。

$form = ActiveForm::begin(['action' =>['book/update']]) 
相關問題