Skip to content

Instantly share code, notes, and snippets.

@surferxo3
Last active November 13, 2017 17:17
Show Gist options
  • Save surferxo3/e7026875dee58f6b513e33439491bea0 to your computer and use it in GitHub Desktop.
Save surferxo3/e7026875dee58f6b513e33439491bea0 to your computer and use it in GitHub Desktop.
Code to handle File Input Validation inside Model in Yii2 Multiple Input widget
<?php
/*#############################
* Developer: Mohammad Sharaf Ali
* Designation: Web Developer
* Version: 1.0
*/#############################
/* REQUIREMENTS
* https://github.com/unclead/yii2-multiple-input
* All code to be placed inside your Model Class
*/
const FILE_ALLOWED_EXT = ['pdf', 'xls', 'xlsx', 'doc', 'docx', 'jpp', 'jpeg', 'png'];
const FILE_ALLOWED_SIZE = 1024 * 1024 * 20; // 20 MB
public $allowedMidDocFiles;
public function validateFile()
{
$successFlag = true;
foreach ($_FILES['Middocuments'] as $key => $value) {
foreach ($value['allowedMidDocFiles'] as $file) {
$_FILES['Middocuments'][$key]['uploadFile'][] = $file['uploadFile'];
}
unset($_FILES['Middocuments'][$key]['allowedMidDocFiles']);
}
$files = UploadedFile::getInstances($this, 'uploadFile');
if (!empty($files)) {
foreach ($files as $index => $file) {
$error = null;
$fileValidator = new FileValidator();
$fileValidator->skipOnEmpty = false;
$fileValidator->checkExtensionByMimeType = false;
$fileValidator->extensions = self::FILE_ALLOWED_EXT;
$fileValidator->maxSize = self::FILE_ALLOWED_SIZE;
$fileValidator->validate($file, $error);
if (!empty($error)) {
$successFlag = false;
$key = 'allowedMidDocFiles[' . $index . '][uploadFile]';
$this->addError($key, $error);
}
}
}
return $successFlag;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment