0

all Yii2 version 2.0.15.1 php 7.0.27

I don't know why this error happen. I recheck this error : Invalid JSON data, it will come out only when do a valiation function checkAva.

here my code

MyModel.php

public function rules(){
    return [
     [['docs'],'file','maxFiles'=>10,'skipOnEmpty'=>true],
     [['available'], 'checkAva','skipOnEmpty' => true,'on'=>'create'],] // if this validation activated error will come out 
}

function checkAva

public function checkAva($attribute, $params)
    {
        $caid = $this->budget_id;
        $available  = Budget::find()
                ->select(['available'])
                ->where('id = :caid', [':caid' => $caid])
                ->one();
        if ($this->available != $available->available){
         $this->addError('available', 'pls change');
        }
    }

function initialPreview

public function initialPreview($data,$field,$type='file'){
        $initial = [];
        $files = Json::decode($data);
        if(is_array($files)){
            foreach ($files as $key => $value) {
                if($type=='file'){
                    $initial[] = "<div class='file-preview-other'><h2><i class='glyphicon glyphicon-file'></i></h2></div>";
                }elseif($type=='config'){
                    $initial[] = [
                        'caption'=> $value,
                        'width'  => '1200px',
                        'url'    => Url::to(['/memo/deletefile','id'=>$this->id,'fileName'=>$key,'field'=>$field]),
                        'key'    => $key
                    ];
                }
                else{
                    $initial[] = Html::img(self::getUploadUrl().$this->ref.'/'.$value,['class'=>'file-preview-image', 'alt'=>$model->file_name, 'title'=>$model->file_name]);
                }
            }
        }
        return $initial;
    }

_form

use yii\helpers\Json;
use kartik\widgets\FileInput;
                    <?= $form->field($model, 'docs[]')->widget(FileInput::classname(), [
                        'options' => [
                            //'accept' => 'image/*',
                            'multiple' => true
                        ],
                        'pluginOptions' => [
                           'initialPreview'=>$model->initialPreview($model->docs,'docs[]','file'),  // if comment this code no error come out I thing it something about formatter?
                           'initialPreviewConfig'=>$model->initialPreview($model->docs,'docs','config'), // if comment this code no error come out I thing it something about formatter?
                            'allowedFileExtensions'=>['pdf','doc','docx','xls','xlsx','jpeg','png','jpg','txt','rtf','tiff','tif'],
                            'initialPreviewAsData'=>true,
                            'maxFileSize'=>15000,
                            'showPreview' => true,
                            'showCaption' => true,
                            'showRemove' => true,
                            'showUpload' => false,
                            'overwriteInitial'=>true
                         ]
                        ]); ?>

in controller $model->docs will call uploadMultipleFile

  public function actionCreate()
     {

    $model->docs = $this->uploadMultipleFile($model);
     }


private function uploadMultipleFile($model,$tempFile=null){
             $files = [];
             $json = '';
             $tempFile = Json::decode($tempFile);
             $UploadedFiles = UploadedFile::getInstances($model,'docs');
             if($UploadedFiles!==null){
                foreach ($UploadedFiles as $file) {
                    try {   $oldFileName = $file->basename.'.'.$file->extension;
                            $newFileName = md5($file->basename.time()).'.'.$file->extension;
                            $file->saveAs(Memoopex::UPLOAD_FOLDER.'/'.$model->ref.'/'.$newFileName);
                            $files[$newFileName] = $oldFileName ;
                    } catch (Exception $e) {
                        //
                    }
                }
                $json = json::encode(ArrayHelper::merge($tempFile,$files));
             }else{
                $json = $tempFile;
             }
            return $json;
    }

error screen enter image description here

0

1 Answer 1

1

You need to provide JSON data when you are decoding using JSON::decode() so your line

'initialPreview'=>$model->initialPreview($model->docs,'docs[]','file'), 

is sending the parameter $model->docs which needs to be a valid json as you are decoding it inside your function initialPreview()

 $files = Json::decode($data);

$data isn't a valid JSON in your case make sure you have a valid JSON string and it will work.

Sign up to request clarification or add additional context in comments.

2 Comments

so I put Json::encode in my _from I don't sure that a correct way or not but working. 'initialPreview' => $model->initialPreview($model->docs = Json::encode($model->docs),'docs','file'), 'initialPreviewConfig' => $model->initialPreview($model->docs = Json::encode($model->docs),'docs','config'), thank you,sir
you can just pass Json::encode($model->docs) in the parameter @ChonjaroenChauynoo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.