我有3个相似的页面,分别是页面A,页面B和页面C。所有这些页面都是为了创建新数据。
如果还使用页面怎么办?
想法是这样的:
\
Controller.php
Page A ----> actionCreate() -----> render to 'create'
Page B ----> actionCreate() -----> render to 'create-obituary'
Page C ----> actionCreate() -----> render to 'create-anniversary'
问题是,我希望所有这三个页面仅使用一个控制器(即actionCreate())。这意味着我想对所有这3页(A,B和C页)进行其他操作。
答案 0 :(得分:0)
我建议将一些参数传递给操作:
public function actionCreate($type = 'create')
{
$typeToPageMapping = [
'create' => 1,
'departed' => 8,
'anniversary' => 4,
]
$model = new Memoriam(['scenario'=>'create']);
if ($type == 'anniversary') {
$modelAnn = new Anniversary();
}
if ($model->load(Yii::$app->request->post()) && ($type != 'anniversary' || $modelAnn->load(Yii::$app->request->post()))) {
$model->picture1 = UploadedFile::getInstance($model, 'picture1');
if ($model->validate()) {
$model->picture1 = $this->savePicture($model);
$model->page = $typeToPageMapping[$type];
$model->save();
if ($type == 'anniversary') {
$modelAnn->decease_id = $model->ID;
$modelAnn->save();
}
if($model->save(false)){
return $this->redirect(['site/profile', 'id' => $model->ID]);
}
}
}
return $this->render('create', [
'model' => $model,
'type' => $type,
'anniversary' => $modelAnn ?? null,
]);
}
protected function savePicture($model)
{
$session = Yii::$app->session;
if($model->picture1 == null) {
return null;
}
$dir = "img/".$session['UserID']."/memoriam/";
if(!file_exists($dir))
{
$old = umask(0);
mkdir($dir, 0777, true);
umask($old);
}
$path = md5(date("YmdHis")) . '.' . $model->picture1->extension;
$model->picture1->saveAs($dir.$path);
return $path;
}