Exemplo n.º 1
0
 public function actionView($id = 0)
 {
     $this->layout = false;
     if ($id) {
         $member = Member::findOne($id);
         if ($member !== null) {
             //编辑场景
             $member->setScenario('update');
         } else {
             return '未找到数据~';
         }
     } else {
         $member = new Member();
         //注册场景
         $member->setScenario('register');
     }
     //Post提交
     if (Yii::$app->request->getIsPost()) {
         $member->setAttributes(Yii::$app->request->post());
         $member->photo = UploadedFile::getInstanceByName('photo');
         Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
         if ($member->validate()) {
             //通过验证
             /**
              * 判断是否选择了文件上传
              * 如果未通过注销当前attributes,这里主要是兼容update场景
              */
             if ($member->photo) {
                 if (!file_exists('uploads/')) {
                     mkdir('uploads/', '777');
                 }
                 $filename = time() . '.' . $member->photo->extension;
                 $member->photo->saveAs('uploads/' . $filename);
                 $member->photo = 'uploads/' . $filename;
             } else {
                 unset($member->photo);
             }
             $result = $member->save();
             if ($result) {
                 Yii::$app->response->data = ['status' => 200, 'message' => '保存成功'];
             } else {
                 Yii::$app->response->data = ['status' => 202, 'message' => '保存失败'];
             }
         } else {
             //验证未通过
             Yii::$app->response->data = ['status' => 201, 'message' => $member->getErrors()];
         }
         return;
     }
     //创建视图
     return $this->render('view', ['user' => $member]);
 }