OSDN Git Service

Откорректированы сообщения и их перевод
[invent/invent.git] / controllers / TypesController.php
1 <?php
2
3 namespace app\controllers;
4
5 use Yii;
6 use app\models\Types;
7 use app\models\TypesSearch;
8 use yii\web\Controller;
9 use yii\web\NotFoundHttpException;
10 use yii\filters\VerbFilter;
11 use app\models\User;
12
13 /**
14  * TypesController implements the CRUD actions for Types model.
15  */
16 class TypesController extends Controller
17 {
18     /**
19      * {@inheritdoc}
20      */
21     public function behaviors()
22     {
23         return [
24             'verbs' => [
25                 'class'   => VerbFilter::className(),
26                 'actions' => [
27                     'delete' => [ 'POST' ],
28                 ],
29             ],
30         ];
31     }
32
33     /**
34      * Добавление типа, если необходимо
35      * @param array $options
36      *        string 'name' - наименование
37      * @return integer|boolean - Идентификатор типа или FALSE в случае неудачи
38      */
39      public function addIfNeed($options)
40      {
41         $result = [
42             'id' => FALSE,
43             'error' => Yii::t('types', 'Types: key field "type" missing: ') . print_r($options, TRUE),
44         ];
45         if (is_array($options) && isset($options[ 'type' ]))
46         {
47             $model = Types::find()
48                 ->where([ 'like', 'name', $options[ 'type' ] ])
49                 ->all();
50             if (count($model) > 0)
51             {
52                 $result['id'] = $model[0]->id;
53                 $result['error'] = '';
54             }
55             else
56             {
57                 $model = new Types();
58                 $model->name = $options[ 'type' ];
59                 if ($model->validate() && $model->save())
60                 {
61                     $result['id'] = $model->id;
62                     $result['error'] = '';
63                 }
64                 else
65                 {
66                     $result['error'] = Yii::t('types', 'Failed to add entry "{type}": ', $options) . print_r($model->errors['name'], TRUE);
67                 }
68             }
69         }
70         return $result;
71      }
72
73     /**
74      * Список всех типов предметов/оборудования.
75      * @return mixed
76      */
77     public function actionIndex()
78     {
79         if (! User::canPermission('createRecord'))
80         {
81             return $this->redirect(['site/index']);
82         }
83         $searchModel  = new TypesSearch();
84         if (isset(Yii::$app->request->queryParams['id'])) {
85             $id = Yii::$app->request->queryParams['id'];
86             $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
87             //$dataProvider->query->select(Types::tableName() . '.id');
88             $pageSize = $dataProvider->pagination->pageSize;
89             $dataProvider->pagination = FALSE;
90             $rows = $dataProvider->getModels();
91             $page = 0;
92             foreach ($rows as $key => $val) {
93                 if ($id == $val->id) {
94                     $page = ceil(($key + 1) / $pageSize);
95                     break;
96                 }
97             }
98             return $this->redirect(['index', 'page' => $page]);
99         }
100         $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
101
102         return $this->render('index', [
103             'searchModel'  => $searchModel,
104             'dataProvider' => $dataProvider,
105         ]);
106     }
107
108     /**
109      * Показ одного типа предмета/оборудования (не используется).
110      * @param integer $id
111      * @return mixed
112      * @throws NotFoundHttpException если отсутствует тип предмета/оборудования
113      */
114     public function actionView($id)
115     {
116         if (! User::canPermission('updateRecord'))
117         {
118             return $this->redirect(['index']);
119         }
120         return $this->render('view', [
121             'model' => $this->findModel($id),
122         ]);
123     }
124
125     /**
126      * Создание нового типа предмета/оборудования.
127      * При успешном создании, происходит переход к списку всех типов предметов/оборудования.
128      * @return mixed
129      */
130     public function actionCreate()
131     {
132         if (! User::canPermission('createRecord'))
133         {
134             return $this->redirect(['site/index']);
135         }
136         $model = new Types();
137
138         if ($model->load(Yii::$app->request->post()) && $model->save())
139         {
140             return $this->redirect([ 'index', 'id' => $model->id ]);
141         }
142
143         return $this->render('create', [
144             'model' => $model,
145         ]);
146     }
147
148     /**
149      * Изменение существующего типа предмета/оборудования.
150      * При успешном изменении, происходит переход к списку всех типов предметов/оборудования.
151      * @param integer $id
152      * @return mixed
153      * @throws NotFoundHttpException если отсутствует тип предмета/оборудования
154      */
155     public function actionUpdate($id)
156     {
157         if (! User::canPermission('updateRecord'))
158         {
159             return $this->redirect(['site/index']);
160         }
161         $model = $this->findModel($id);
162
163         if ($model->load(Yii::$app->request->post()) && $model->save())
164         {
165             return $this->redirect([ 'index', 'id' => $model->id ]);
166         }
167
168         return $this->render('update', [
169             'model' => $model,
170         ]);
171     }
172
173     /**
174      * Удаление существующего типа предмета/оборудования.
175      * При успешном удалении, происходит переход к списку всех типов предметов/оборудования.
176      * @param integer $id
177      * @return mixed
178      * @throws NotFoundHttpException если отсутствует тип предмета/оборудования
179      */
180     public function actionDelete($id)
181     {
182         if (! User::canPermission('updateRecord'))
183         {
184             return $this->redirect(['site/index']);
185         }
186         $this->findModel($id)->delete();
187
188         return $this->redirect([ 'index' ]);
189     }
190
191     /**
192      * Finds the Types model based on its primary key value.
193      * If the model is not found, a 404 HTTP exception will be thrown.
194      * @param integer $id
195      * @return Types the loaded model
196      * @throws NotFoundHttpException if the model cannot be found
197      */
198     protected function findModel($id)
199     {
200         if (($model = Types::findOne($id)) !== null)
201         {
202             return $model;
203         }
204
205         throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
206     }
207 }