Magento 2 Custom UI grid form.php validate upload file extension
-
07-04-2021 - |
Question
I want to check the upload file extension in form.php, I have three upload file options I want to check the upload file is pdf or not. Thanks in advance. my form.php file is
namespace Vendor\Extension\Block\Adminhtml\Blog\Edit;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Registry;
use Magento\Framework\Data\FormFactory;
use Vendor\Extension\Block\Adminhtml\Status;
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
protected $_systemStore;
public function __construct(
Context $context,
Registry $registry,
FormFactory $formFactory,
Status $options,
array $data = []
)
{
$this->options = $options;
parent::__construct($context, $registry, $formFactory, $data);
}
protected function _prepareForm()
{
$dateFormat = $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT);
$model = $this->_coreRegistry->registry('row_data');
$form = $this->_formFactory->create(
['data' => [
'id' => 'edit_form',
'enctype' => 'multipart/form-data',
'action' => $this->getData('action'),
'method' => 'post'
]
]
);
$form->setHtmlIdPrefix('mtgrid_');
if ($model->getId()) {
$fieldset = $form->addFieldset(
'base_fieldset',
['legend' => __('Edit Row Data'), 'class' => 'fieldset-wide']
);
$fieldset->addField('id', 'hidden', ['name' => 'id']);
} else {
$fieldset = $form->addFieldset(
'base_fieldset',
['legend' => __('Add Row Data'), 'class' => 'fieldset-wide']
);
}
$fieldset->addField(
'prapproveno',
'text',
[
'name' => 'prapproveno',
'label' => __('Prior Approve No.'),
'id' => 'prapproveno',
'title' => __('Prior Approve No.'),
'class' => '',
]
);
//$wysiwygConfig = $this->_wysiwygConfig->getConfig(['tab_id' => $this->getTabId()]);
$fieldset->addField(
'submitdate',
'date',
[
'name' => 'submitdate',
'label' => __('Submit Date'),
'date_format' => $dateFormat,
'time_format' => 'HH:mm:ss',
'class' => 'validate-date validate-date-range date-range-custom_theme-from',
'class' => 'required-entry',
]
);
$fieldset->addField(
'chnlmanager',
'text',
[
'name' => 'chnlmanager',
'label' => __('Channel Maneger'),
'id' => 'chnlmanager',
'title' => __('Channel Manager'),
'class' => 'required-entry',
]
);
$fieldset->addField(
'status',
'select',
[
'name' => 'status',
'label' => __('Status'),
'id' => 'status',
'title' => __('Status'),
'values' => [1=>"Enable",0=>"Disable"],
'class' => 'status',
'required' => true,
]
);
$fieldset->addField(
'company',
'select',
[
'name' => 'company',
'label' => __('Company'),
'id' => 'company',
'title' => __('Company'),
'values' => $this->options->getOptionArray(),
'class' => 'required-entry',
'required' => true,
]
);
$fieldset->addField(
'branch',
'text',
[
'name' => 'branch',
'label' => __('Branch'),
'id' => 'branch',
'title' => __('Branch'),
'class' => 'required-entry',
]
);
$fieldset->addField(
'avpno',
'text',
[
'name' => 'avpno',
'label' => __('AVP/Reseller No.'),
'id' => 'avpno',
'title' => __('AVP/Reseller No.'),
'class' => 'required-entry',
]
);
$fieldset->addField(
'budgetfrom',
'select',
[
'name' => 'budgetfrom',
'label' => __('Budget From'),
'id' => 'budgetfrom',
'title' => __('Budget From'),
'values' => $this->options->getOptionArray(),
'class' => 'required-entry',
'required' => true,
]
);
$fieldset->addField(
'marketingactivity',
'select',
[
'name' => 'marketingactivity',
'label' => __('Marketing Activity'),
'id' => 'budgetfrom',
'title' => __('Budget From'),
'values' => $this->options->getOptionArray(),
'class' => 'required-entry',
'required' => true,
]
);
$fieldset->addField(
'description',
'text',
[
'name' => 'description',
'label' => __('Description'),
'id' => 'description',
'title' => __('Description'),
'class' => 'required-entry',
]
);
$fieldset->addField(
'file1',
'file',
[
'name' => 'file1',
'label' => __('Attachments'),
'id' => 'file1',
'title' => __('Attachments'),
'note' => 'PDF format only'
]
);
$fieldset->addField(
'file2',
'file',
[
'name' => 'file2',
'id' => 'file2',
'note' => 'PDF format only'
]
);
$fieldset->addField(
'file3',
'file',
[
'name' => 'file3',
'id' => 'file3',
'note' => 'PDF format only'
]
);
$form->setValues($model->getData());
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
Solution
You can validate the file extension in the controller before saving the form.
app/code/Vendor/Extension/Controller/Adminhtml/Blog/Save.php
Check the below code.
<?php
namespace Vendor\Extension\Controller\Adminhtml\Blog;
use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
class Save extends Action
{
protected $fileSystem;
protected $uploaderFactory;
protected $allowedExtensions = ['csv'];
protected $fileId = 'file';
public function __construct(
Action\Context $context,
Filesystem $fileSystem,
UploaderFactory $uploaderFactory
) {
$this->fileSystem = $fileSystem;
$this->uploaderFactory = $uploaderFactory;
parent::__construct($context);
}
public function execute()
{
$destinationPath = $this->getDestinationPath();
try {
$uploader = $this->uploaderFactory->create(['fileId' => $this->fileId])
->setAllowCreateFolders(true)
->setAllowedExtensions($this->allowedExtensions)
->addValidateCallback('validate', $this, 'validateFile');
if (!$uploader->save($destinationPath)) {
throw new LocalizedException(
__('File cannot be saved to path: $1', $destinationPath)
);
}
} catch (\Exception $e) {
$this->messageManager->addError(
__($e->getMessage())
);
}
}
public function validateFile($filePath)
{
// @todo
// your custom validation code here
}
public function getDestinationPath()
{
return $this->fileSystem
->getDirectoryWrite(DirectoryList::TMP)
->getAbsolutePath('/');
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange