问候语,
到目前为止,我已经让Yii2应用程序始终在某个Controller中为每个操作呈现一个视图。
但现在我需要在同一个屏幕上渲染2个视图文件,index
和create
。
在Yii1.xx中有renderPartial()
,在Yii2中现在有render()
作为替代,但不知道如何使用它。我知道语法有点像app/Controller::render()
,但它并没有给我敲响声。
我的SiteController中的actionIndex是:
public function actionIndex()
{
$searchModel = new TubeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->redirect(Url::toRoute('tube/index'), [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
此操作会将管/索引页面加载为应用的起始页面。我想加入创建动作。是否可能 - >两个php文件在statup的同一个屏幕上呈现。
非常感谢...
答案 0 :(得分:1)
从您的问题中不清楚您实际想要实现的目标,因此我将根据两种截然不同的情况提出两种解决方案。在这两种情况下,您都需要将表单的action
参数配置为指向tube/create
,否则您的表单将无法正常提交。
场景1 - 您希望在用户访问tube/index
site/index
视图
由于视图tube/index
似乎是关于创建新模型,为简单起见,我将其称为tube / create。
从我的索引页面重定向在我看来是不好的做法。它会使服务器上的负载加倍,并且用户可能会对它们被重定向的原因感到困惑。实现此目的的最简单方法就是在站点控制器的tube/create
操作中呈现index
视图,就像这样;
public function actionIndex(){
$searchModel = new TubeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$model = new Tube();
$model->load(Yii::$app->request->post());
$model->save();
return $this->render('@app/views/tube/create', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
场景2 - 您希望在同一页面上呈现两个视图,一个用于查看某种搜索的结果,另一个用于创建新模型。这是您在Yii1中使用renderPartial()
的原因。你会这样做的;
我坚持在网站/索引操作中渲染tube / create。
public function actionIndex(){
$searchModel = new TubeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$model = new Tube();
$model->load(Yii::$app->request->post());
$model->save();
return $this->render('//tube/index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
然后,您只需在tube/index
视图文件中呈现两个单独的部分视图,就像这样。
/** tube/index **/
echo $this->render('//tube/view', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,]);
echo $this->render('//tube/create', [
'model' => $model]
);
这两个方案假设您的视图文件位于views/tube
文件夹中,并且您已经在控制器文件的顶部加载了必需的模型并带有use
语句。
答案 1 :(得分:0)
我是由MYSELF解决的。
SITECONTROLLER代码:
public function actionIndex()
{
return $this->redirect(Url::toRoute('tube/index'));
}
TUBECONTROLLER CODE:
public function actionIndex()
{
$searchModel = new TubeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$model = new Tube();
if ($model->load(Yii::$app->request->post())) {
$model->save();
}
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
这样,索引和创建视图就在同一页面中,每一件事都可以正常工作。