Blame view

examples/UploadFileParsingForm.php 1.89 KB
8cb5acbf   Mihail   add exaples templ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  <?php
  namespace backend\models;
  
  use yii\base\ErrorException;
  use yii\base\Model;
  use yii\web\UploadedFile;
  use Yii;
  use common\components\CustomVarDamp;
  
  /**
   * UploadForm is the model behind the upload form.
   */
  class UploadFileParsingForm extends Model
  {
      /**
       * @var UploadedFile file attribute
       */
      // chosen file
      public $file;
      // file path after save
      public $file_path;
      // 0 - custom file (user should choose in $file field)
      // 1 - csv template file from data/template.csv
      // 2 - xml template file from data/template.xml
      // 3 - xlsx template file from data/template.xlsx
d8aa85f3   Mihail   add examples for ...
26
27
      // 4 - xls template file from data/template.xls
      // 5 - txt template file from data/template.txt
8cb5acbf   Mihail   add exaples templ...
28
29
30
31
32
33
34
35
36
37
38
      public $file_type = 0;
  
  
      public function rules()
      {
          $client_func = <<< JS
          function(attribute, value) {
              return $('input[name=UploadFileParsingForm[file_type]]').val() == '0';
          }
  JS;
          return [
d8aa85f3   Mihail   add examples for ...
39
              ['file_type', 'in', 'range' => range( 0, 5 ) ],
8cb5acbf   Mihail   add exaples templ...
40
41
42
              ['file', 'required', 'when' => function(){
                  return !$this->file_type;
              } , 'whenClient' => $client_func],
d8aa85f3   Mihail   add examples for ...
43
              [['file'], 'file', 'extensions' => ['csv', 'xlsx', 'xml', 'xls', 'txt'], 'checkExtensionByMimeType' => false ],
8cb5acbf   Mihail   add exaples templ...
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
              ['file_path', 'safe'],
  
          ];
      }
  
      public function attributeLabels()
      {
          return [
              'file' => Yii::t('app', 'Custom file'),
          ];
      }
  
      public function readFile( $options = [] ){
  
          $data = Yii::$app->multiparser->parse( $this->file_path, $options );
  
          if( !is_array( $data ) || count($data) == 0 ){
61323a64   Mihail   redid read method...
61
              throw new ErrorException("Parser return empty array. Check file and configuration settings (config.php)");
8cb5acbf   Mihail   add exaples templ...
62
63
64
65
66
67
68
69
70
71
72
73
          }
  
          if(  !$this->file_path  && file_exists( $this->file_path ) )
              unlink( $this->file_path );
  
          return $data;
      }
  
  
  
  
  }