Commit ae27b007efa5922fd056e8c13723ad49181af527

Authored by Mihail
1 parent 87fcd9da

add ajax handler for deleting files from server

backend/assets/CheckPriceAsset.php renamed to backend/assets/ParserAsset.php
... ... @@ -10,14 +10,14 @@ namespace backend\assets;
10 10  
11 11 use yii\web\AssetBundle;
12 12  
13   -class CheckPriceAsset extends AssetBundle {
  13 +class ParserAsset extends AssetBundle {
14 14 public $basePath = '@webroot';
15 15 public $baseUrl = '@web';
16 16 public $css = [
17 17 'css/site.css',
18 18 ];
19 19 public $js = [
20   - 'js/check-price.js',
  20 + 'js/parser.js',
21 21 ];
22 22 public $depends = [
23 23 'yii\web\YiiAsset',
... ...
backend/controllers/ParserController.php
... ... @@ -269,14 +269,14 @@ class ParserController extends BaseController
269 269  
270 270 public function actionServerFiles ()
271 271 {
272   - $arr_id = [];
  272 + $arr_id_files = [];
273 273 // получим список файлов которые ожидают к загрузке
274 274 foreach (glob(Yii::getAlias('@auto_upload') . '/*') as $server_file) {
275 275 $file_id = basename($server_file,".csv");
276   - $arr_id[] = (int) $file_id;
  276 + $arr_id_files[] = (int) $file_id;
277 277 }
278   -
279   - $query = ImporterFiles::find()->where(['in', 'id', $arr_id])->orderBy(['upload_time' => SORT_DESC]);
  278 + Yii::$app->cache->set( 'files_to_delete',json_encode( $arr_id_files ) );
  279 + $query = ImporterFiles::find()->where(['in', 'id', $arr_id_files])->orderBy(['upload_time' => SORT_DESC]);
280 280  
281 281 $provider = new ActiveDataProvider([
282 282 'query' => $query,
... ... @@ -289,24 +289,35 @@ class ParserController extends BaseController
289 289 'dataProvider' => $provider]);
290 290 }
291 291  
292   - public function actionDelete ($id)
  292 + public function actionDelete ()
293 293 {
294   - if(Yii::$app->request->isAjax){
295   - CustomVarDamp::dumpAndDie(1);
296   - }
297   -
298   - $files_model = new ImporterFiles();
299   - try {
  294 + if ( Yii::$app->request->isAjax ) {
300 295  
301   - $files_model->delete($id);
302   - unlink(Yii::getAlias('@auto_upload') . '/' . $id . '.csv' );
303   -
304   - } catch (ErrorException $e) {
  296 + $files_model = new ImporterFiles();
  297 + if ( isset(Yii::$app->request->post()['id'] )) {
  298 + $id = Yii::$app->request->post()['id'];
  299 + try {
  300 + $files_model->delete($id);
  301 + unlink(Yii::getAlias('@auto_upload') . '/' . $id . '.csv' );
  302 +
  303 + // удалим этот id и из кэша
  304 + if( $arr_id_files = Yii::$app->cache->get( 'files_to_delete' ) ){
  305 + $arr_id_files = json_decode($arr_id_files);
  306 + if (isset( $arr_id_files[$id] ) ) {
  307 + unset( $arr_id_files[$id] );
  308 + // положем уже обновленный массив
  309 + Yii::$app->cache->set( 'files_to_delete',json_encode( $arr_id_files ) );
  310 + }
  311 + }
  312 + // сообщим скрипту что все ОК
  313 + echo 1;
  314 + } catch (ErrorException $e) {
305 315  
306   - CustomVarDamp::dump($e->getMessage());
  316 + CustomVarDamp::dump($e->getMessage());
307 317  
  318 + }
  319 + }
308 320 }
309 321  
310   - $this->redirect('server-files');
311 322 }
312 323 }
... ...
backend/views/check-price/index.php
... ... @@ -2,11 +2,10 @@
2 2 use yii\helpers\Html;
3 3 use yii\grid\GridView;
4 4 use yii\grid\SerialColumn;
5   -use yii\grid\ActionColumn;
6 5 use yii\widgets\Pjax;
7 6 use yii\bootstrap\Modal;
8 7 use yii\helpers\Url;
9   -use backend\assets\CheckPriceAsset;
  8 +use backend\assets\ParserAsset;
10 9  
11 10  
12 11 /* @var $this yii\web\View */
... ... @@ -16,7 +15,8 @@ use backend\assets\CheckPriceAsset;
16 15 $this->title = 'Проверка прайсов';
17 16 $this->params['breadcrumbs'][] = $this->title;
18 17 // зарегистрируем скрипт для обработки загрузки модального окна
19   -CheckPriceAsset::register($this);
  18 +ParserAsset::register($this);
  19 +Pjax::begin();
20 20 ?>
21 21 <div class="catalog-index">
22 22  
... ... @@ -30,7 +30,6 @@ CheckPriceAsset::register($this);
30 30 ['content' => function ($model) {
31 31 $url = Url::to(['view', 'id' => $model->id, 'date_update' => $model->price_date_update]);
32 32 return Html::a('<span class="glyphicon glyphicon-remove"> Просмотреть </span>', '#', [
33   - 'title' => Yii::t('yii', 'Просмотреть прайс'),
34 33 'class' => 'modalButton',
35 34 'value' => $url,
36 35 ]);
... ... @@ -76,6 +75,7 @@ CheckPriceAsset::register($this);
76 75 echo "<div id='modalContent'></div>";
77 76  
78 77 Modal::end();
  78 + Pjax::end();
79 79 ?>
80 80  
81 81  
... ...
backend/views/parser/server-files.php
... ... @@ -4,15 +4,17 @@ use yii\grid\GridView;
4 4 use yii\grid\SerialColumn;
5 5 use yii\grid\ActionColumn;
6 6 use yii\widgets\Pjax;
  7 +use backend\assets\ParserAsset;
7 8  
8 9  
9 10 /* @var $this yii\web\View */
10 11 /* @var $searchModel backend\models\CatalogSearch */
11 12 /* @var $dataProvider yii\data\ActiveDataProvider */
12 13  
13   -$this->title = 'Проверка прайсов';
  14 +$this->title = 'Файлы на сервере';
14 15 $this->params['breadcrumbs'][] = $this->title;
15   -Pjax::begin();
  16 +ParserAsset::register($this);
  17 +Pjax::begin(['id' => 'server_files_grid']);
16 18  
17 19 ?>
18 20 <div class="catalog-index">
... ... @@ -30,19 +32,15 @@ Pjax::begin();
30 32 ['label' =>'Дата загрузки',
31 33 'attribute' => 'upload_time' ],
32 34  
33   - ['class' => ActionColumn::className(),
34   - 'template'=>'{delete}',
35   - 'buttons' => [
36   - 'delete' => function ($url, $model, $key) {
37   - return Html::a('<span class="glyphicon glyphicon-remove"></span>', $url, [
38   - 'title' => Yii::t('yii', 'Удалить файл'),
39   - 'data-confirm' => 'Вы уверены что хотите удалить этот файл?',
40   - 'data-method' => 'post',
41   - 'data-pjax' => '0',
42   - ]);
43   - },
44   - ],
45   - ]
  35 + ['content' => function ($model) {
  36 + //Url::to(['delete', 'id' => $model->id, 'date_update' => $model->price_date_update]);
  37 + return Html::a('<span class="glyphicon glyphicon-remove"> Удалить </span>', '#', [
  38 + 'value' => $model->id,
  39 + 'class' => 'deleteLink',
  40 + ]);
  41 + },
  42 + ],
  43 +
46 44  
47 45 ]] );?>
48 46  
... ...
backend/web/js/check-price.js deleted
1   -$(function(){
2   -
3   - // get the click of the create button
4   - $('.modalButton').click(function (){
5   - $('#modal').modal('show')
6   - .find('#modalContent')
7   - .load($(this).attr('value'));
8   - });
9   -});
backend/web/js/parser.js 0 → 100644
  1 +$(function(){
  2 +
  3 + // для каждой строки обрабатываем клик по ссылке
  4 + $('.modalButton').click(function (){
  5 + // находим контейнер с модальным контентом и подгружаем в него по оджаксу результат
  6 + $('#modal').modal('show')
  7 + .find('#modalContent')
  8 + .load($(this).attr('value')); // в 'value' - у нас указан путь с гет параметрами к конроллеру
  9 + });
  10 +
  11 + $('.deleteLink').click(function ()
  12 + {
  13 + if ( confirm('Вы уверены что хотите удалить этот файл?') ){
  14 + var data = $(this).attr('value');// здесь у нас id удаляемой модели
  15 +
  16 + $.post( 'delete',{'id':data} )
  17 + .done(function(result) {
  18 + if(result == 1)
  19 + {
  20 + $.pjax.reload({container:'#server_files_grid'});
  21 + }else
  22 + {
  23 + $("#message").html(result);
  24 + }
  25 + }).fail(function()
  26 + {
  27 + console.log("server error");
  28 + });
  29 + }
  30 +
  31 +
  32 +
  33 +
  34 +});
  35 +});
... ...