PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/entity/controllers/ItemsController.php

https://gitlab.com/nitm/yii2-cms
PHP | 229 lines | 208 code | 21 blank | 0 comment | 30 complexity | fe4eefadfcf4cd631fbbc76f4dc3ff35 MD5 | raw file
  1. <?php
  2. namespace nitm\cms\modules\entity\controllers;
  3. use Yii;
  4. use \nitm\cms\actions\ChangeStatusAction;
  5. use \nitm\cms\actions\DeleteAction;
  6. use \nitm\cms\actions\SortByNumAction;
  7. use \nitm\cms\helpers\Image;
  8. use \nitm\cms\helpers\Upload;
  9. use \nitm\cms\modules\entity\EntityModule;
  10. use \nitm\cms\widgets\DateTimePicker;
  11. use yii\validators\FileValidator;
  12. use yii\web\UploadedFile;
  13. use yii\helpers\Html;
  14. use \nitm\cms\components\Controller;
  15. use \nitm\cms\modules\entity\models\Category;
  16. use \nitm\cms\modules\entity\models\Item;
  17. use yii\widgets\ActiveForm;
  18. class ItemsController extends Controller
  19. {
  20. public $modelClass = 'nitm\cms\modules\entity\models\Item';
  21. public $categoryClass = 'nitm\cms\modules\entity\models\Category';
  22. public function actions()
  23. {
  24. return [
  25. 'delete' => [
  26. 'class' => DeleteAction::className(),
  27. 'successMessage' => Yii::t('nitm/cms', 'Item deleted')
  28. ],
  29. 'up' => SortByNumAction::className(),
  30. 'down' => SortByNumAction::className(),
  31. 'on' => ChangeStatusAction::className(),
  32. 'off' => ChangeStatusAction::className(),
  33. ];
  34. }
  35. public function actionIndex($id)
  36. {
  37. return $this->render('index', [
  38. 'category' => $this->findCategory($id)
  39. ]);
  40. }
  41. public function actionCreate($id)
  42. {
  43. $category = $this->findCategory($id);
  44. $model = new Item(['category_id' => $id]);
  45. if ($model->load(Yii::$app->request->post())) {
  46. if(Yii::$app->request->isAjax){
  47. Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  48. return ActiveForm::validate($model);
  49. }
  50. else {
  51. $this->parseData($model);
  52. if ($model->save()) {
  53. $this->flash('success', Yii::t('nitm/cms', 'Item created'));
  54. return $this->redirect(['/admin/'.$this->module->id.'/items/form/update/', 'id' => $model->primaryKey]);
  55. } else {
  56. $this->flash('error', Yii::t('nitm/cms', 'Create error. {0}', $model->formatErrors()));
  57. return $this->refresh();
  58. }
  59. }
  60. }
  61. else {
  62. return $this->render('create', [
  63. 'model' => $model,
  64. 'category' => $category,
  65. 'dataForm' => $this->generateForm($category->fields),
  66. 'cats' => $this->getSameCats($category)
  67. ]);
  68. }
  69. }
  70. public function actionUpdate($id, $modelClass=null, $with=[], $viewOptions=[])
  71. {
  72. $model = $this->findModel($id);
  73. if ($model->load(Yii::$app->request->post())) {
  74. if(Yii::$app->request->isAjax){
  75. Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  76. return ActiveForm::validate($model);
  77. }
  78. else {
  79. $this->parseData($model);
  80. if ($model->save()) {
  81. $this->flash('success', Yii::t('nitm/cms', 'Item updated'));
  82. return $this->redirect(['/admin/'.$this->module->id.'/items/form/update', 'id' => $model->primaryKey]);
  83. } else {
  84. $this->flash('error', Yii::t('nitm/cms', 'Update error. {0}', $model->formatErrors()));
  85. return $this->refresh();
  86. }
  87. }
  88. }
  89. else {
  90. return $this->render('update', [
  91. 'model' => $model,
  92. 'dataForm' => $this->generateForm($model->category->fields, $model->data),
  93. 'cats' => $this->getSameCats($model->category)
  94. ]);
  95. }
  96. }
  97. public function actionPhotos($id)
  98. {
  99. return $this->render('photos', [
  100. 'model' => $this->findModel($id),
  101. ]);
  102. }
  103. public function actionDeleteDataFile($file)
  104. {
  105. foreach(Item::find()->where(['like', 'data', $file])->all() as $model) {
  106. foreach ($model->data as $name => $value) {
  107. if (!is_array($value) && strpos($value, '/' . $file) !== false) {
  108. Upload::delete($value);
  109. $model->data->{$name} = '';
  110. }
  111. }
  112. $model->update();
  113. }
  114. return $this->formatResponse(Yii::t('nitm/cms', 'Deleted'));
  115. }
  116. private function generateForm($fields, $data = null)
  117. {
  118. $result = '';
  119. foreach($fields as $field)
  120. {
  121. $value = !empty($data->{$field->name}) ? $data->{$field->name} : null;
  122. if ($field->type === 'string') {
  123. $result .= '<div class="form-group"><label>'. $field->title .'</label>'. Html::input('text', "Data[{$field->name}]", $value, ['class' => 'form-control']) .'</div>';
  124. }
  125. elseif ($field->type === 'text') {
  126. $result .= '<div class="form-group"><label>'. $field->title .'</label>'. Html::textarea("Data[{$field->name}]", $value, ['class' => 'form-control']) .'</div>';
  127. }
  128. elseif ($field->type === 'html') {
  129. $result .= '<div class="form-group"><label>'. $field->title .'</label>';
  130. $result .= \nitm\cms\widgets\Redactor::widget([
  131. 'name' => "Data[{$field->name}]",
  132. 'value' => $value,
  133. ]);
  134. $result .= '</div>';
  135. }
  136. elseif ($field->type === 'boolean') {
  137. $result .= '<div class="checkbox"><label>'. Html::checkbox("Data[{$field->name}]", $value, ['uncheck' => 0]) .' '. $field->title .'</label></div>';
  138. }
  139. elseif ($field->type === 'select') {
  140. $options = ['' => Yii::t('nitm/cms', 'Select')];
  141. foreach($field->options as $option){
  142. $options[$option] = $option;
  143. }
  144. $result .= '<div class="form-group"><label>'. $field->title .'</label><select name="Data['.$field->name.']" class="form-control">'. Html::renderSelectOptions($value, $options) .'</select></div>';
  145. }
  146. elseif ($field->type === 'checkbox') {
  147. $options = '';
  148. foreach($field->options as $option){
  149. $checked = $value && in_array($option, $value);
  150. $options .= '<br><label>'. Html::checkbox("Data[{$field->name}][]", $checked, ['value' => $option]) .' '. $option .'</label>';
  151. }
  152. $result .= '<div class="checkbox well well-sm"><b>'. $field->title .'</b>'. $options .'</div>';
  153. }
  154. elseif ($field->type === 'file') {
  155. $result .= '<div class="form-group"><label>'. $field->title .'</label><p>';
  156. if($value != ''){
  157. $basename = basename($value);
  158. $isImage = preg_match('/\.(jpg|jpeg|png|gif|bmp)$/', $basename);
  159. if($isImage) {
  160. $result .= Html::a(Html::img(Image::thumb($value, 240, 180)), Upload::getFileUrl($value), ['class' => 'fancybox']);
  161. } else {
  162. $result .= Html::a($basename, [$value], ['target' => 'blank']);
  163. }
  164. $result .= ' ' . Html::a($isImage ? 'Удалить' : '<i class="fa fa-remove"></i>', ['/admin/' . $this->module->id . '/items/delete-data-file', 'file' => $basename], ['class' => 'confirm-delete', 'data-reload' => 1, 'title' => Yii::t('nitm/cms', 'Delete')]);
  165. }
  166. $result .= '</p>' . Html::fileInput("Data[{$field->name}]"). '</div>';
  167. }
  168. elseif ($field->type === 'date') {
  169. $result .= '<div class="form-group"><label>'. $field->title .'</label>';
  170. $result .= DateTimePicker::widget(['name' => "Data[{$field->name}]", 'value' => $value]);
  171. $result .= '</div>';
  172. }
  173. }
  174. return $result;
  175. }
  176. private function parseData(&$model)
  177. {
  178. $data = Yii::$app->request->post('Data');
  179. if(isset($_FILES['Data']))
  180. {
  181. foreach($_FILES['Data']['name'] as $fieldName => $sourceName){
  182. $field = $model->category->getFieldByName($fieldName);
  183. $validator = new FileValidator(['extensions' => $field->options ? $field->options : null]);
  184. $uploadInstance = UploadedFile::getInstanceByName('Data['.$fieldName.']');
  185. if($uploadInstance && $validator->validate($uploadInstance) && ($result = Upload::file($uploadInstance, 'entity', false))) {
  186. if(!empty($model->data->{$fieldName})){
  187. Upload::delete($model->data->{$fieldName});
  188. }
  189. $data[$fieldName] = $result;
  190. } else {
  191. $data[$fieldName] = !empty($model->data->{$fieldName}) ? $model->data->{$fieldName} : '';
  192. }
  193. }
  194. }
  195. $model->data = $data;
  196. }
  197. private function getSameCats($cat)
  198. {
  199. $result = [];
  200. $fieldsHash = md5(json_encode($cat->fields));
  201. foreach(Category::cats() as $cat){
  202. if(md5(json_encode($cat->fields)) == $fieldsHash && (!count($cat->children) || EntityModule::setting('itemsInFolder'))) {
  203. $result[$cat->id] = $cat->title;
  204. }
  205. }
  206. return $result;
  207. }
  208. }