2017-09-02 60 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']]) 
相关问题