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