BookController.php
3.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
/**
* Created by PhpStorm.
* User: stes
* Date: 08.06.18
* Time: 12:39
*/
namespace frontend\controllers;
use common\models\Book;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\UploadedFile;
class BookController extends Controller
{
/**
* @inheritdoc
*/
public function beforeAction($action)
{
if ($action->id == 'add' or $action->id == 'edit') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
public function actionAdd()
{
/**
* @var \common\models\Author $user ;
*/
$user = \Yii::$app->user->identity;
if (\Yii::$app->user->isGuest) {
$this->redirect([ 'site/index' ]);
}
$model = new Book();
if (\Yii::$app->request->isPost) {
if ($model->load(\Yii::$app->request->post(), '') and $model->validate()) {
$model->author_id = $user->id;
$model->status = $model::STATUS_MODERATION;
return ( $model->save() && $model->saveImage(UploadedFile::getInstanceByName('file')) );
} else {
return false;
}
}
return $this->render(
'add',
[
'book' => [],
]
);
}
public function actionEdit($id)
{
$model = Book::findOne($id);
if ($model->author_id !== \Yii::$app->user->getId()) {
return $this->redirect([ 'site/index' ]);
}
if (\Yii::$app->request->isPost) {
if ($model->load(\Yii::$app->request->post(), '') and $model->validate()) {
return ( $model->save() && $model->saveImage(UploadedFile::getInstanceByName('file')) );
} else {
return false;
}
}
return $this->render(
'add',
[
'book' => $model->attributes,
]
);
}
public function actionIndex()
{
$dataProvider = new ActiveDataProvider(
[
'query' => Book::find()
->with(['author', 'alias'])
->where([ 'status' => Book::STATUS_ACTIVE ]),
'pagination' => [
'pageSize' => 10,
],
]
);
return $this->render(
'index',
[
'dataProvider' => $dataProvider,
]
);
}
public function actionView($id){
$model = Book::find()->with(['author', 'activeComments']) ->where(['id' => $id])->one();
return $this->render('view', ['model' => $model]);
}
}