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;
}
