Magento – Magento 2: Add a Custom Import Sample File to vendor/magento/module-import-export/Files/Sample directoy

importmagento-2.1magento2overridessample

I created a custom import module from two custom models and tables. The imports works fine, and without any error or problem now. But I noticed that next to Entity Type dropdown, appears a "Dowload Sample File".

enter image description here

And, when I click in that (when is selected my custom entity type), the page show me a "There is no sample file for this entity." error.

So, after check the file vendor/magento/module-import-export/Controller/Adminhtml/Import/Download.php it's look like Magento is searching the sample file in the directory:

vendor/magento/module-import-export/Files/Sample

So, the "quick" way of correcting this problem, I suppose, is to add the files of my modules in that directory. However, my question is: is this "right"? My logic tells me that it's not good to touch ANYTHING that's in the vendor folder. But then, what is the other alternative that could apply?, since it seems that with these lines:

fileName = $this->getRequest()->getParam('filename') . '.csv';
$moduleDir = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, self::SAMPLE_FILES_MODULE);
$fileAbsolutePath = $moduleDir . '/Files/Sample/' . $fileName;
$directoryRead = $this->readFactory->create($moduleDir);
$filePath = $directoryRead->getRelativePath($fileAbsolutePath);

Force to search directly in that directory.

Some suggestions?

Best Answer

I find some solution. Create one preference for overrides download file.

Add this code to di.xml file

<preference for="Magento\ImportExport\Controller\Adminhtml\Import\Download" type="NameSpace\ModuleName\Controller\Adminhtml\Import\Download"/>

Create directory with csv file

NameSpace/ModuleName/view/adminhtml/Files/Sample/your_csv_file.csv

Create Download.php file at NameSpace\ModuleName\Controller\Adminhtml\Import

And put this code

<?php

namespace NameSpace\ModuleName\Controller\Adminhtml\Import;

use Magento\Framework\Component\ComponentRegistrar;
use Magento\ImportExport\Controller\Adminhtml\Import as ImportController;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\ImportExport\Controller\Adminhtml\Import\Download as Mdownload;

class Download extends Mdownload
{
    protected $moduleReader;
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
        \Magento\Framework\Filesystem\Directory\ReadFactory $readFactory,
        \Magento\Framework\Component\ComponentRegistrar $componentRegistrar,
        \Magento\Framework\Module\Dir\Reader $moduleReader
    ) {
        parent::__construct(
            $context,
            $fileFactory,
            $resultRawFactory,
            $readFactory,
            $componentRegistrar

        );
        $this->moduleReader = $moduleReader;
    }
    public function getDirectory()
    {
        $viewDir = $this->moduleReader->getModuleDir(
            \Magento\Framework\Module\Dir::MODULE_VIEW_DIR,
            'NameSpace_ModuleName'
        );
        return $viewDir . '/adminhtml/Files/Sample/';
    }

    /**
     * Download sample file action
     *
     * @return \Magento\Framework\Controller\Result\Raw
     */
    public function execute()
    {
        $fileName = $this->getRequest()->getParam('filename') . '.csv';
        $moduleDir = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, self::SAMPLE_FILES_MODULE);
        $fileAbsolutePath = $moduleDir . '/Files/Sample/' . $fileName;
        $directoryRead = $this->readFactory->create($moduleDir);
        $filePath = $directoryRead->getRelativePath($fileAbsolutePath);

        if (!$directoryRead->isFile($filePath)) {

            $fileAbsolutePath = $this->getDirectory() . $fileName;
            $directoryRead = $this->readFactory->create($this->getDirectory());
            $filePath = $directoryRead->getRelativePath($fileAbsolutePath);
            if (!$directoryRead->isFile($filePath)) {
            /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
                $this->messageManager->addError(__('There is no sample file for this entity.'));
                $resultRedirect = $this->resultRedirectFactory->create();
                $resultRedirect->setPath('*/import');
                return $resultRedirect;
            }
        }

        $fileSize = isset($directoryRead->stat($filePath)['size'])
            ? $directoryRead->stat($filePath)['size'] : null;

        $this->fileFactory->create(
            $fileName,
            null,
            DirectoryList::VAR_DIR,
            'application/octet-stream',
            $fileSize
        );
        /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
        $resultRaw = $this->resultRawFactory->create();
        $resultRaw->setContents($directoryRead->readFile($filePath));
        return $resultRaw;
    }
}

thats it, for any clarity related to this answer please mention in comment.

Related Topic