OSDN Git Service

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