Ejemplo n.º 1
0
 private function handlePostComment(CommentForm $commentForm)
 {
     $request = \Yii::$app->request;
     if ($request->getIsPost() && $request->post('cs-comment-form-submit') !== null) {
         $commentForm->attributes = $request->post('CommentForm');
         if ($commentForm->validate()) {
             $comment = new Comment();
             $comment->relModelClass = get_class($this->model);
             $comment->relModelId = $this->model->id;
             $comment->text = $commentForm->text;
             $comment->insert();
             $comment->refresh();
             // обработка файла
             if ($uploadedFile = UploadedFile::getInstance($commentForm, 'attachment')) {
                 $fileName = md5(uniqid() . $comment->id . rand(1, 1000)) . '.' . $uploadedFile->extension;
                 $folder = '/uploads/sc/' . date('Y') . '/' . date('m') . '/' . date('d');
                 if (!is_dir(\Yii::getAlias('@webroot') . $folder)) {
                     if (!@mkdir(\Yii::getAlias('@webroot') . $folder, 0777, true)) {
                         throw new Exception('Не удалось создать директорию');
                     }
                 }
                 if (!$uploadedFile->saveAs(\Yii::getAlias('@webroot') . $folder . '/' . $fileName)) {
                     throw new Exception('Не удалось скопировать файл');
                 }
                 $commentAttachment = new CommentAttachment();
                 $commentAttachment->commentId = $comment->id;
                 $commentAttachment->fileName = $fileName;
                 $commentAttachment->filePath = \Yii::getAlias('@webroot') . $folder . '/' . $fileName;
                 $commentAttachment->fileUrl = $folder . '/' . $fileName;
                 $commentAttachment->fileExtension = $uploadedFile->extension;
                 $commentAttachment->insert();
             }
             \Yii::$app->controller->refresh();
         }
     }
     return $commentForm;
 }
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getComment()
 {
     return $this->hasOne(Comment::className(), ['id' => 'commentId']);
 }